CameraService.cpp revision 8129e799f2774235c8cce3bf25fd98ef4ca2471b
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 <stdio.h> 21#include <string.h> 22#include <sys/types.h> 23#include <pthread.h> 24 25#include <binder/AppOpsManager.h> 26#include <binder/IPCThreadState.h> 27#include <binder/IServiceManager.h> 28#include <binder/MemoryBase.h> 29#include <binder/MemoryHeapBase.h> 30#include <cutils/atomic.h> 31#include <cutils/properties.h> 32#include <gui/Surface.h> 33#include <hardware/hardware.h> 34#include <media/AudioSystem.h> 35#include <media/IMediaHTTPService.h> 36#include <media/mediaplayer.h> 37#include <utils/Errors.h> 38#include <utils/Log.h> 39#include <utils/String16.h> 40#include <utils/Trace.h> 41#include <system/camera_vendor_tags.h> 42#include <system/camera_metadata.h> 43#include <system/camera.h> 44 45#include "CameraService.h" 46#include "api1/CameraClient.h" 47#include "api1/Camera2Client.h" 48#include "api_pro/ProCamera2Client.h" 49#include "api2/CameraDeviceClient.h" 50#include "utils/CameraTraces.h" 51#include "CameraDeviceFactory.h" 52 53namespace android { 54 55// ---------------------------------------------------------------------------- 56// Logging support -- this is for debugging only 57// Use "adb shell dumpsys media.camera -v 1" to change it. 58volatile int32_t gLogLevel = 0; 59 60#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__); 61#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__); 62 63static void setLogLevel(int level) { 64 android_atomic_write(level, &gLogLevel); 65} 66 67// ---------------------------------------------------------------------------- 68 69static int getCallingPid() { 70 return IPCThreadState::self()->getCallingPid(); 71} 72 73static int getCallingUid() { 74 return IPCThreadState::self()->getCallingUid(); 75} 76 77extern "C" { 78static void camera_device_status_change( 79 const struct camera_module_callbacks* callbacks, 80 int camera_id, 81 int new_status) { 82 sp<CameraService> cs = const_cast<CameraService*>( 83 static_cast<const CameraService*>(callbacks)); 84 85 cs->onDeviceStatusChanged( 86 camera_id, 87 new_status); 88} 89} // extern "C" 90 91// ---------------------------------------------------------------------------- 92 93// This is ugly and only safe if we never re-create the CameraService, but 94// should be ok for now. 95static CameraService *gCameraService; 96 97CameraService::CameraService() 98 :mSoundRef(0), mModule(0) 99{ 100 ALOGI("CameraService started (pid=%d)", getpid()); 101 gCameraService = this; 102 103 for (size_t i = 0; i < MAX_CAMERAS; ++i) { 104 mStatusList[i] = ICameraServiceListener::STATUS_PRESENT; 105 } 106 107 this->camera_device_status_change = android::camera_device_status_change; 108} 109 110void CameraService::onFirstRef() 111{ 112 LOG1("CameraService::onFirstRef"); 113 114 BnCameraService::onFirstRef(); 115 116 if (hw_get_module(CAMERA_HARDWARE_MODULE_ID, 117 (const hw_module_t **)&mModule) < 0) { 118 ALOGE("Could not load camera HAL module"); 119 mNumberOfCameras = 0; 120 } 121 else { 122 ALOGI("Loaded \"%s\" camera module", mModule->common.name); 123 mNumberOfCameras = mModule->get_number_of_cameras(); 124 if (mNumberOfCameras > MAX_CAMERAS) { 125 ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).", 126 mNumberOfCameras, MAX_CAMERAS); 127 mNumberOfCameras = MAX_CAMERAS; 128 } 129 for (int i = 0; i < mNumberOfCameras; i++) { 130 setCameraFree(i); 131 } 132 133 if (mModule->common.module_api_version >= 134 CAMERA_MODULE_API_VERSION_2_1) { 135 mModule->set_callbacks(this); 136 } 137 138 VendorTagDescriptor::clearGlobalVendorTagDescriptor(); 139 140 if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_2) { 141 setUpVendorTags(); 142 } 143 144 CameraDeviceFactory::registerService(this); 145 } 146} 147 148CameraService::~CameraService() { 149 for (int i = 0; i < mNumberOfCameras; i++) { 150 if (mBusy[i]) { 151 ALOGE("camera %d is still in use in destructor!", i); 152 } 153 } 154 155 VendorTagDescriptor::clearGlobalVendorTagDescriptor(); 156 gCameraService = NULL; 157} 158 159void CameraService::onDeviceStatusChanged(int cameraId, 160 int newStatus) 161{ 162 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__, 163 cameraId, newStatus); 164 165 if (cameraId < 0 || cameraId >= MAX_CAMERAS) { 166 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId); 167 return; 168 } 169 170 if ((int)getStatus(cameraId) == newStatus) { 171 ALOGE("%s: State transition to the same status 0x%x not allowed", 172 __FUNCTION__, (uint32_t)newStatus); 173 return; 174 } 175 176 /* don't do this in updateStatus 177 since it is also called from connect and we could get into a deadlock */ 178 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) { 179 Vector<sp<BasicClient> > clientsToDisconnect; 180 { 181 Mutex::Autolock al(mServiceLock); 182 183 /* Remove cached parameters from shim cache */ 184 mShimParams.removeItem(cameraId); 185 186 /* Find all clients that we need to disconnect */ 187 sp<BasicClient> client = mClient[cameraId].promote(); 188 if (client.get() != NULL) { 189 clientsToDisconnect.push_back(client); 190 } 191 192 int i = cameraId; 193 for (size_t j = 0; j < mProClientList[i].size(); ++j) { 194 sp<ProClient> cl = mProClientList[i][j].promote(); 195 if (cl != NULL) { 196 clientsToDisconnect.push_back(cl); 197 } 198 } 199 } 200 201 /* now disconnect them. don't hold the lock 202 or we can get into a deadlock */ 203 204 for (size_t i = 0; i < clientsToDisconnect.size(); ++i) { 205 sp<BasicClient> client = clientsToDisconnect[i]; 206 207 client->disconnect(); 208 /** 209 * The remote app will no longer be able to call methods on the 210 * client since the client PID will be reset to 0 211 */ 212 } 213 214 ALOGV("%s: After unplug, disconnected %zu clients", 215 __FUNCTION__, clientsToDisconnect.size()); 216 } 217 218 updateStatus( 219 static_cast<ICameraServiceListener::Status>(newStatus), cameraId); 220 221} 222 223int32_t CameraService::getNumberOfCameras() { 224 return mNumberOfCameras; 225} 226 227status_t CameraService::getCameraInfo(int cameraId, 228 struct CameraInfo* cameraInfo) { 229 if (!mModule) { 230 return -ENODEV; 231 } 232 233 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 234 return BAD_VALUE; 235 } 236 237 struct camera_info info; 238 status_t rc = mModule->get_camera_info(cameraId, &info); 239 cameraInfo->facing = info.facing; 240 cameraInfo->orientation = info.orientation; 241 return rc; 242} 243 244 245status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) { 246 status_t ret = OK; 247 struct CameraInfo info; 248 if ((ret = getCameraInfo(cameraId, &info)) != OK) { 249 return ret; 250 } 251 252 CameraMetadata shimInfo; 253 int32_t orientation = static_cast<int32_t>(info.orientation); 254 if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) { 255 return ret; 256 } 257 258 uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ? 259 ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK; 260 if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) { 261 return ret; 262 } 263 264 ssize_t index = -1; 265 { // Scope for service lock 266 Mutex::Autolock lock(mServiceLock); 267 index = mShimParams.indexOfKey(cameraId); 268 // Release service lock so initializeShimMetadata can be called correctly. 269 } 270 271 if (index < 0) { 272 int64_t token = IPCThreadState::self()->clearCallingIdentity(); 273 ret = initializeShimMetadata(cameraId); 274 IPCThreadState::self()->restoreCallingIdentity(token); 275 if (ret != OK) { 276 return ret; 277 } 278 } 279 280 Vector<Size> sizes; 281 Vector<int32_t> formats; 282 const char* supportedPreviewFormats; 283 { // Scope for service lock 284 Mutex::Autolock lock(mServiceLock); 285 index = mShimParams.indexOfKey(cameraId); 286 287 mShimParams[index].getSupportedPreviewSizes(/*out*/sizes); 288 289 mShimParams[index].getSupportedPreviewFormats(/*out*/formats); 290 } 291 292 // Always include IMPLEMENTATION_DEFINED 293 formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED); 294 295 const size_t INTS_PER_CONFIG = 4; 296 297 // Build available stream configurations metadata 298 size_t streamConfigSize = sizes.size() * formats.size() * INTS_PER_CONFIG; 299 int32_t streamConfigs[streamConfigSize]; 300 size_t configIndex = 0; 301 for (size_t i = 0; i < formats.size(); ++i) { 302 for (size_t j = 0; j < sizes.size(); ++j) { 303 streamConfigs[configIndex++] = formats[i]; 304 streamConfigs[configIndex++] = sizes[j].width; 305 streamConfigs[configIndex++] = sizes[j].height; 306 streamConfigs[configIndex++] = 307 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT; 308 } 309 } 310 311 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS, 312 streamConfigs, streamConfigSize)) != OK) { 313 return ret; 314 } 315 316 int64_t fakeMinFrames[0]; 317 // TODO: Fixme, don't fake min frame durations. 318 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS, 319 fakeMinFrames, 0)) != OK) { 320 return ret; 321 } 322 323 int64_t fakeStalls[0]; 324 // TODO: Fixme, don't fake stall durations. 325 if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS, 326 fakeStalls, 0)) != OK) { 327 return ret; 328 } 329 330 *cameraInfo = shimInfo; 331 return OK; 332} 333 334status_t CameraService::getCameraCharacteristics(int cameraId, 335 CameraMetadata* cameraInfo) { 336 if (!cameraInfo) { 337 ALOGE("%s: cameraInfo is NULL", __FUNCTION__); 338 return BAD_VALUE; 339 } 340 341 if (!mModule) { 342 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__); 343 return -ENODEV; 344 } 345 346 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 347 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId); 348 return BAD_VALUE; 349 } 350 351 int facing; 352 status_t ret = OK; 353 if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0 || 354 getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1 ) { 355 /** 356 * Backwards compatibility mode for old HALs: 357 * - Convert CameraInfo into static CameraMetadata properties. 358 * - Retrieve cached CameraParameters for this camera. If none exist, 359 * attempt to open CameraClient and retrieve the CameraParameters. 360 * - Convert cached CameraParameters into static CameraMetadata 361 * properties. 362 */ 363 ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__); 364 365 if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) { 366 return ret; 367 } 368 369 } else { 370 /** 371 * Normal HAL 2.1+ codepath. 372 */ 373 struct camera_info info; 374 ret = mModule->get_camera_info(cameraId, &info); 375 *cameraInfo = info.static_camera_characteristics; 376 } 377 378 return ret; 379} 380 381status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) { 382 if (!mModule) { 383 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__); 384 return -ENODEV; 385 } 386 387 desc = VendorTagDescriptor::getGlobalVendorTagDescriptor(); 388 return OK; 389} 390 391int CameraService::getDeviceVersion(int cameraId, int* facing) { 392 struct camera_info info; 393 if (mModule->get_camera_info(cameraId, &info) != OK) { 394 return -1; 395 } 396 397 int deviceVersion; 398 if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_0) { 399 deviceVersion = info.device_version; 400 } else { 401 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 402 } 403 404 if (facing) { 405 *facing = info.facing; 406 } 407 408 return deviceVersion; 409} 410 411bool CameraService::isValidCameraId(int cameraId) { 412 int facing; 413 int deviceVersion = getDeviceVersion(cameraId, &facing); 414 415 switch(deviceVersion) { 416 case CAMERA_DEVICE_API_VERSION_1_0: 417 case CAMERA_DEVICE_API_VERSION_2_0: 418 case CAMERA_DEVICE_API_VERSION_2_1: 419 case CAMERA_DEVICE_API_VERSION_3_0: 420 case CAMERA_DEVICE_API_VERSION_3_1: 421 case CAMERA_DEVICE_API_VERSION_3_2: 422 return true; 423 default: 424 return false; 425 } 426 427 return false; 428} 429 430bool CameraService::setUpVendorTags() { 431 vendor_tag_ops_t vOps = vendor_tag_ops_t(); 432 433 // Check if vendor operations have been implemented 434 if (mModule->get_vendor_tag_ops == NULL) { 435 ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__); 436 return false; 437 } 438 439 ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops"); 440 mModule->get_vendor_tag_ops(&vOps); 441 ATRACE_END(); 442 443 // Ensure all vendor operations are present 444 if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL || 445 vOps.get_section_name == NULL || vOps.get_tag_name == NULL || 446 vOps.get_tag_type == NULL) { 447 ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions." 448 , __FUNCTION__); 449 return false; 450 } 451 452 // Read all vendor tag definitions into a descriptor 453 sp<VendorTagDescriptor> desc; 454 status_t res; 455 if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc)) 456 != OK) { 457 ALOGE("%s: Could not generate descriptor from vendor tag operations," 458 "received error %s (%d). Camera clients will not be able to use" 459 "vendor tags", __FUNCTION__, strerror(res), res); 460 return false; 461 } 462 463 // Set the global descriptor to use with camera metadata 464 VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc); 465 return true; 466} 467 468status_t CameraService::initializeShimMetadata(int cameraId) { 469 int pid = getCallingPid(); 470 int uid = getCallingUid(); 471 status_t ret = validateConnect(cameraId, uid); 472 if (ret != OK) { 473 return ret; 474 } 475 476 bool needsNewClient = false; 477 sp<Client> client; 478 479 String16 internalPackageName("media"); 480 { // Scope for service lock 481 Mutex::Autolock lock(mServiceLock); 482 if (mClient[cameraId] != NULL) { 483 client = static_cast<Client*>(mClient[cameraId].promote().get()); 484 } 485 if (client == NULL) { 486 needsNewClient = true; 487 ret = connectHelperLocked(/*cameraClient*/NULL, // Empty binder callbacks 488 cameraId, 489 internalPackageName, 490 uid, 491 pid, 492 client); 493 494 if (ret != OK) { 495 return ret; 496 } 497 } 498 499 if (client == NULL) { 500 ALOGE("%s: Could not connect to client camera device.", __FUNCTION__); 501 return BAD_VALUE; 502 } 503 504 String8 rawParams = client->getParameters(); 505 CameraParameters params(rawParams); 506 mShimParams.add(cameraId, params); 507 } 508 509 // Close client if one was opened solely for this call 510 if (needsNewClient) { 511 client->disconnect(); 512 } 513 return OK; 514} 515 516status_t CameraService::validateConnect(int cameraId, 517 /*inout*/ 518 int& clientUid) const { 519 520 int callingPid = getCallingPid(); 521 522 if (clientUid == USE_CALLING_UID) { 523 clientUid = getCallingUid(); 524 } else { 525 // We only trust our own process to forward client UIDs 526 if (callingPid != getpid()) { 527 ALOGE("CameraService::connect X (pid %d) rejected (don't trust clientUid)", 528 callingPid); 529 return PERMISSION_DENIED; 530 } 531 } 532 533 if (!mModule) { 534 ALOGE("Camera HAL module not loaded"); 535 return -ENODEV; 536 } 537 538 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 539 ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).", 540 callingPid, cameraId); 541 return -ENODEV; 542 } 543 544 char value[PROPERTY_VALUE_MAX]; 545 property_get("sys.secpolicy.camera.disabled", value, "0"); 546 if (strcmp(value, "1") == 0) { 547 // Camera is disabled by DevicePolicyManager. 548 ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid); 549 return -EACCES; 550 } 551 552 ICameraServiceListener::Status currentStatus = getStatus(cameraId); 553 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) { 554 ALOGI("Camera is not plugged in," 555 " connect X (pid %d) rejected", callingPid); 556 return -ENODEV; 557 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) { 558 ALOGI("Camera is enumerating," 559 " connect X (pid %d) rejected", callingPid); 560 return -EBUSY; 561 } 562 // Else don't check for STATUS_NOT_AVAILABLE. 563 // -- It's done implicitly in canConnectUnsafe /w the mBusy array 564 565 return OK; 566} 567 568bool CameraService::canConnectUnsafe(int cameraId, 569 const String16& clientPackageName, 570 const sp<IBinder>& remoteCallback, 571 sp<BasicClient> &client) { 572 String8 clientName8(clientPackageName); 573 int callingPid = getCallingPid(); 574 575 if (mClient[cameraId] != 0) { 576 client = mClient[cameraId].promote(); 577 if (client != 0) { 578 if (remoteCallback == client->getRemote()) { 579 LOG1("CameraService::connect X (pid %d) (the same client)", 580 callingPid); 581 return true; 582 } else { 583 // TODOSC: need to support 1 regular client, 584 // multiple shared clients here 585 ALOGW("CameraService::connect X (pid %d) rejected" 586 " (existing client).", callingPid); 587 return false; 588 } 589 } 590 mClient[cameraId].clear(); 591 } 592 593 /* 594 mBusy is set to false as the last step of the Client destructor, 595 after which it is guaranteed that the Client destructor has finished ( 596 including any inherited destructors) 597 598 We only need this for a Client subclasses since we don't allow 599 multiple Clents to be opened concurrently, but multiple BasicClient 600 would be fine 601 */ 602 if (mBusy[cameraId]) { 603 ALOGW("CameraService::connect X (pid %d, \"%s\") rejected" 604 " (camera %d is still busy).", callingPid, 605 clientName8.string(), cameraId); 606 return false; 607 } 608 609 return true; 610} 611 612status_t CameraService::connectHelperLocked(const sp<ICameraClient>& cameraClient, 613 int cameraId, 614 const String16& clientPackageName, 615 int clientUid, 616 int callingPid, 617 /*out*/ 618 sp<Client>& client) { 619 620 int facing = -1; 621 int deviceVersion = getDeviceVersion(cameraId, &facing); 622 623 // If there are other non-exclusive users of the camera, 624 // this will tear them down before we can reuse the camera 625 if (isValidCameraId(cameraId)) { 626 // transition from PRESENT -> NOT_AVAILABLE 627 updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE, 628 cameraId); 629 } 630 631 switch(deviceVersion) { 632 case CAMERA_DEVICE_API_VERSION_1_0: 633 client = new CameraClient(this, cameraClient, 634 clientPackageName, cameraId, 635 facing, callingPid, clientUid, getpid()); 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 client = new Camera2Client(this, cameraClient, 643 clientPackageName, cameraId, 644 facing, callingPid, clientUid, getpid(), 645 deviceVersion); 646 break; 647 case -1: 648 ALOGE("Invalid camera id %d", cameraId); 649 return BAD_VALUE; 650 default: 651 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 652 return INVALID_OPERATION; 653 } 654 655 status_t status = connectFinishUnsafe(client, client->getRemote()); 656 if (status != OK) { 657 // this is probably not recoverable.. maybe the client can try again 658 // OK: we can only get here if we were originally in PRESENT state 659 updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId); 660 return status; 661 } 662 663 mClient[cameraId] = client; 664 LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, 665 getpid()); 666 667 return OK; 668} 669 670status_t CameraService::connect( 671 const sp<ICameraClient>& cameraClient, 672 int cameraId, 673 const String16& clientPackageName, 674 int clientUid, 675 /*out*/ 676 sp<ICamera>& device) { 677 678 String8 clientName8(clientPackageName); 679 int callingPid = getCallingPid(); 680 681 LOG1("CameraService::connect E (pid %d \"%s\", id %d)", callingPid, 682 clientName8.string(), cameraId); 683 684 status_t status = validateConnect(cameraId, /*inout*/clientUid); 685 if (status != OK) { 686 return status; 687 } 688 689 690 sp<Client> client; 691 { 692 Mutex::Autolock lock(mServiceLock); 693 sp<BasicClient> clientTmp; 694 if (!canConnectUnsafe(cameraId, clientPackageName, 695 cameraClient->asBinder(), 696 /*out*/clientTmp)) { 697 return -EBUSY; 698 } else if (client.get() != NULL) { 699 device = static_cast<Client*>(clientTmp.get()); 700 return OK; 701 } 702 703 status = connectHelperLocked(cameraClient, 704 cameraId, 705 clientPackageName, 706 clientUid, 707 callingPid, 708 client); 709 if (status != OK) { 710 return status; 711 } 712 713 } 714 // important: release the mutex here so the client can call back 715 // into the service from its destructor (can be at the end of the call) 716 717 device = client; 718 return OK; 719} 720 721status_t CameraService::connectFinishUnsafe(const sp<BasicClient>& client, 722 const sp<IBinder>& remoteCallback) { 723 status_t status = client->initialize(mModule); 724 if (status != OK) { 725 return status; 726 } 727 if (remoteCallback != NULL) { 728 remoteCallback->linkToDeath(this); 729 } 730 731 return OK; 732} 733 734status_t CameraService::connectPro( 735 const sp<IProCameraCallbacks>& cameraCb, 736 int cameraId, 737 const String16& clientPackageName, 738 int clientUid, 739 /*out*/ 740 sp<IProCameraUser>& device) 741{ 742 if (cameraCb == 0) { 743 ALOGE("%s: Callback must not be null", __FUNCTION__); 744 return BAD_VALUE; 745 } 746 747 String8 clientName8(clientPackageName); 748 int callingPid = getCallingPid(); 749 750 LOG1("CameraService::connectPro E (pid %d \"%s\", id %d)", callingPid, 751 clientName8.string(), cameraId); 752 status_t status = validateConnect(cameraId, /*inout*/clientUid); 753 if (status != OK) { 754 return status; 755 } 756 757 sp<ProClient> client; 758 { 759 Mutex::Autolock lock(mServiceLock); 760 { 761 sp<BasicClient> client; 762 if (!canConnectUnsafe(cameraId, clientPackageName, 763 cameraCb->asBinder(), 764 /*out*/client)) { 765 return -EBUSY; 766 } 767 } 768 769 int facing = -1; 770 int deviceVersion = getDeviceVersion(cameraId, &facing); 771 772 switch(deviceVersion) { 773 case CAMERA_DEVICE_API_VERSION_1_0: 774 ALOGE("Camera id %d uses HALv1, doesn't support ProCamera", 775 cameraId); 776 return -EOPNOTSUPP; 777 break; 778 case CAMERA_DEVICE_API_VERSION_2_0: 779 case CAMERA_DEVICE_API_VERSION_2_1: 780 case CAMERA_DEVICE_API_VERSION_3_0: 781 case CAMERA_DEVICE_API_VERSION_3_1: 782 case CAMERA_DEVICE_API_VERSION_3_2: 783 client = new ProCamera2Client(this, cameraCb, String16(), 784 cameraId, facing, callingPid, USE_CALLING_UID, getpid()); 785 break; 786 case -1: 787 ALOGE("Invalid camera id %d", cameraId); 788 return BAD_VALUE; 789 default: 790 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 791 return INVALID_OPERATION; 792 } 793 794 status_t status = connectFinishUnsafe(client, client->getRemote()); 795 if (status != OK) { 796 return status; 797 } 798 799 mProClientList[cameraId].push(client); 800 801 LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId, 802 getpid()); 803 } 804 // important: release the mutex here so the client can call back 805 // into the service from its destructor (can be at the end of the call) 806 device = client; 807 return OK; 808} 809 810status_t CameraService::connectDevice( 811 const sp<ICameraDeviceCallbacks>& cameraCb, 812 int cameraId, 813 const String16& clientPackageName, 814 int clientUid, 815 /*out*/ 816 sp<ICameraDeviceUser>& device) 817{ 818 819 String8 clientName8(clientPackageName); 820 int callingPid = getCallingPid(); 821 822 LOG1("CameraService::connectDevice E (pid %d \"%s\", id %d)", callingPid, 823 clientName8.string(), cameraId); 824 825 status_t status = validateConnect(cameraId, /*inout*/clientUid); 826 if (status != OK) { 827 return status; 828 } 829 830 sp<CameraDeviceClient> client; 831 { 832 Mutex::Autolock lock(mServiceLock); 833 { 834 sp<BasicClient> client; 835 if (!canConnectUnsafe(cameraId, clientPackageName, 836 cameraCb->asBinder(), 837 /*out*/client)) { 838 return -EBUSY; 839 } 840 } 841 842 int facing = -1; 843 int deviceVersion = getDeviceVersion(cameraId, &facing); 844 845 // If there are other non-exclusive users of the camera, 846 // this will tear them down before we can reuse the camera 847 if (isValidCameraId(cameraId)) { 848 // transition from PRESENT -> NOT_AVAILABLE 849 updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE, 850 cameraId); 851 } 852 853 switch(deviceVersion) { 854 case CAMERA_DEVICE_API_VERSION_1_0: 855 case CAMERA_DEVICE_API_VERSION_2_0: 856 case CAMERA_DEVICE_API_VERSION_2_1: 857 case CAMERA_DEVICE_API_VERSION_3_0: 858 case CAMERA_DEVICE_API_VERSION_3_1: 859 ALOGW("Camera using old HAL version: %d", deviceVersion); 860 return -EOPNOTSUPP; 861 case CAMERA_DEVICE_API_VERSION_3_2: 862 client = new CameraDeviceClient(this, cameraCb, String16(), 863 cameraId, facing, callingPid, USE_CALLING_UID, getpid()); 864 break; 865 case -1: 866 ALOGE("Invalid camera id %d", cameraId); 867 return BAD_VALUE; 868 default: 869 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 870 return INVALID_OPERATION; 871 } 872 873 status_t status = connectFinishUnsafe(client, client->getRemote()); 874 if (status != OK) { 875 // this is probably not recoverable.. maybe the client can try again 876 // OK: we can only get here if we were originally in PRESENT state 877 updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId); 878 return status; 879 } 880 881 LOG1("CameraService::connectDevice X (id %d, this pid is %d)", cameraId, 882 getpid()); 883 884 mClient[cameraId] = client; 885 } 886 // important: release the mutex here so the client can call back 887 // into the service from its destructor (can be at the end of the call) 888 889 device = client; 890 return OK; 891} 892 893 894status_t CameraService::addListener( 895 const sp<ICameraServiceListener>& listener) { 896 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get()); 897 898 if (listener == 0) { 899 ALOGE("%s: Listener must not be null", __FUNCTION__); 900 return BAD_VALUE; 901 } 902 903 Mutex::Autolock lock(mServiceLock); 904 905 Vector<sp<ICameraServiceListener> >::iterator it, end; 906 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) { 907 if ((*it)->asBinder() == listener->asBinder()) { 908 ALOGW("%s: Tried to add listener %p which was already subscribed", 909 __FUNCTION__, listener.get()); 910 return ALREADY_EXISTS; 911 } 912 } 913 914 mListenerList.push_back(listener); 915 916 /* Immediately signal current status to this listener only */ 917 { 918 Mutex::Autolock m(mStatusMutex) ; 919 int numCams = getNumberOfCameras(); 920 for (int i = 0; i < numCams; ++i) { 921 listener->onStatusChanged(mStatusList[i], i); 922 } 923 } 924 925 return OK; 926} 927status_t CameraService::removeListener( 928 const sp<ICameraServiceListener>& listener) { 929 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get()); 930 931 if (listener == 0) { 932 ALOGE("%s: Listener must not be null", __FUNCTION__); 933 return BAD_VALUE; 934 } 935 936 Mutex::Autolock lock(mServiceLock); 937 938 Vector<sp<ICameraServiceListener> >::iterator it; 939 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) { 940 if ((*it)->asBinder() == listener->asBinder()) { 941 mListenerList.erase(it); 942 return OK; 943 } 944 } 945 946 ALOGW("%s: Tried to remove a listener %p which was not subscribed", 947 __FUNCTION__, listener.get()); 948 949 return BAD_VALUE; 950} 951 952void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) { 953 int callingPid = getCallingPid(); 954 LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid); 955 956 // Declare this before the lock to make absolutely sure the 957 // destructor won't be called with the lock held. 958 Mutex::Autolock lock(mServiceLock); 959 960 int outIndex; 961 sp<BasicClient> client = findClientUnsafe(remoteBinder, outIndex); 962 963 if (client != 0) { 964 // Found our camera, clear and leave. 965 LOG1("removeClient: clear camera %d", outIndex); 966 967 sp<IBinder> remote = client->getRemote(); 968 if (remote != NULL) { 969 remote->unlinkToDeath(this); 970 } 971 972 mClient[outIndex].clear(); 973 } else { 974 975 sp<ProClient> clientPro = findProClientUnsafe(remoteBinder); 976 977 if (clientPro != NULL) { 978 // Found our camera, clear and leave. 979 LOG1("removeClient: clear pro %p", clientPro.get()); 980 981 clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this); 982 } 983 } 984 985 LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid); 986} 987 988sp<CameraService::ProClient> CameraService::findProClientUnsafe( 989 const wp<IBinder>& cameraCallbacksRemote) 990{ 991 sp<ProClient> clientPro; 992 993 for (int i = 0; i < mNumberOfCameras; ++i) { 994 Vector<size_t> removeIdx; 995 996 for (size_t j = 0; j < mProClientList[i].size(); ++j) { 997 wp<ProClient> cl = mProClientList[i][j]; 998 999 sp<ProClient> clStrong = cl.promote(); 1000 if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) { 1001 clientPro = clStrong; 1002 break; 1003 } else if (clStrong == NULL) { 1004 // mark to clean up dead ptr 1005 removeIdx.push(j); 1006 } 1007 } 1008 1009 // remove stale ptrs (in reverse so the indices dont change) 1010 for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) { 1011 mProClientList[i].removeAt(removeIdx[j]); 1012 } 1013 1014 } 1015 1016 return clientPro; 1017} 1018 1019sp<CameraService::BasicClient> CameraService::findClientUnsafe( 1020 const wp<IBinder>& cameraClient, int& outIndex) { 1021 sp<BasicClient> client; 1022 1023 for (int i = 0; i < mNumberOfCameras; i++) { 1024 1025 // This happens when we have already disconnected (or this is 1026 // just another unused camera). 1027 if (mClient[i] == 0) continue; 1028 1029 // Promote mClient. It can fail if we are called from this path: 1030 // Client::~Client() -> disconnect() -> removeClientByRemote(). 1031 client = mClient[i].promote(); 1032 1033 // Clean up stale client entry 1034 if (client == NULL) { 1035 mClient[i].clear(); 1036 continue; 1037 } 1038 1039 if (cameraClient == client->getRemote()) { 1040 // Found our camera 1041 outIndex = i; 1042 return client; 1043 } 1044 } 1045 1046 outIndex = -1; 1047 return NULL; 1048} 1049 1050CameraService::BasicClient* CameraService::getClientByIdUnsafe(int cameraId) { 1051 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL; 1052 return mClient[cameraId].unsafe_get(); 1053} 1054 1055Mutex* CameraService::getClientLockById(int cameraId) { 1056 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL; 1057 return &mClientLock[cameraId]; 1058} 1059 1060sp<CameraService::BasicClient> CameraService::getClientByRemote( 1061 const wp<IBinder>& cameraClient) { 1062 1063 // Declare this before the lock to make absolutely sure the 1064 // destructor won't be called with the lock held. 1065 sp<BasicClient> client; 1066 1067 Mutex::Autolock lock(mServiceLock); 1068 1069 int outIndex; 1070 client = findClientUnsafe(cameraClient, outIndex); 1071 1072 return client; 1073} 1074 1075status_t CameraService::onTransact( 1076 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { 1077 // Permission checks 1078 switch (code) { 1079 case BnCameraService::CONNECT: 1080 case BnCameraService::CONNECT_PRO: 1081 const int pid = getCallingPid(); 1082 const int self_pid = getpid(); 1083 if (pid != self_pid) { 1084 // we're called from a different process, do the real check 1085 if (!checkCallingPermission( 1086 String16("android.permission.CAMERA"))) { 1087 const int uid = getCallingUid(); 1088 ALOGE("Permission Denial: " 1089 "can't use the camera pid=%d, uid=%d", pid, uid); 1090 return PERMISSION_DENIED; 1091 } 1092 } 1093 break; 1094 } 1095 1096 return BnCameraService::onTransact(code, data, reply, flags); 1097} 1098 1099// The reason we need this busy bit is a new CameraService::connect() request 1100// may come in while the previous Client's destructor has not been run or is 1101// still running. If the last strong reference of the previous Client is gone 1102// but the destructor has not been finished, we should not allow the new Client 1103// to be created because we need to wait for the previous Client to tear down 1104// the hardware first. 1105void CameraService::setCameraBusy(int cameraId) { 1106 android_atomic_write(1, &mBusy[cameraId]); 1107 1108 ALOGV("setCameraBusy cameraId=%d", cameraId); 1109} 1110 1111void CameraService::setCameraFree(int cameraId) { 1112 android_atomic_write(0, &mBusy[cameraId]); 1113 1114 ALOGV("setCameraFree cameraId=%d", cameraId); 1115} 1116 1117// We share the media players for shutter and recording sound for all clients. 1118// A reference count is kept to determine when we will actually release the 1119// media players. 1120 1121MediaPlayer* CameraService::newMediaPlayer(const char *file) { 1122 MediaPlayer* mp = new MediaPlayer(); 1123 if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) { 1124 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE); 1125 mp->prepare(); 1126 } else { 1127 ALOGE("Failed to load CameraService sounds: %s", file); 1128 return NULL; 1129 } 1130 return mp; 1131} 1132 1133void CameraService::loadSound() { 1134 Mutex::Autolock lock(mSoundLock); 1135 LOG1("CameraService::loadSound ref=%d", mSoundRef); 1136 if (mSoundRef++) return; 1137 1138 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg"); 1139 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg"); 1140} 1141 1142void CameraService::releaseSound() { 1143 Mutex::Autolock lock(mSoundLock); 1144 LOG1("CameraService::releaseSound ref=%d", mSoundRef); 1145 if (--mSoundRef) return; 1146 1147 for (int i = 0; i < NUM_SOUNDS; i++) { 1148 if (mSoundPlayer[i] != 0) { 1149 mSoundPlayer[i]->disconnect(); 1150 mSoundPlayer[i].clear(); 1151 } 1152 } 1153} 1154 1155void CameraService::playSound(sound_kind kind) { 1156 LOG1("playSound(%d)", kind); 1157 Mutex::Autolock lock(mSoundLock); 1158 sp<MediaPlayer> player = mSoundPlayer[kind]; 1159 if (player != 0) { 1160 player->seekTo(0); 1161 player->start(); 1162 } 1163} 1164 1165// ---------------------------------------------------------------------------- 1166 1167CameraService::Client::Client(const sp<CameraService>& cameraService, 1168 const sp<ICameraClient>& cameraClient, 1169 const String16& clientPackageName, 1170 int cameraId, int cameraFacing, 1171 int clientPid, uid_t clientUid, 1172 int servicePid) : 1173 CameraService::BasicClient(cameraService, cameraClient->asBinder(), 1174 clientPackageName, 1175 cameraId, cameraFacing, 1176 clientPid, clientUid, 1177 servicePid) 1178{ 1179 int callingPid = getCallingPid(); 1180 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId); 1181 1182 mRemoteCallback = cameraClient; 1183 1184 cameraService->setCameraBusy(cameraId); 1185 cameraService->loadSound(); 1186 1187 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId); 1188} 1189 1190// tear down the client 1191CameraService::Client::~Client() { 1192 ALOGV("~Client"); 1193 mDestructionStarted = true; 1194 1195 mCameraService->releaseSound(); 1196 // unconditionally disconnect. function is idempotent 1197 Client::disconnect(); 1198} 1199 1200CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService, 1201 const sp<IBinder>& remoteCallback, 1202 const String16& clientPackageName, 1203 int cameraId, int cameraFacing, 1204 int clientPid, uid_t clientUid, 1205 int servicePid): 1206 mClientPackageName(clientPackageName) 1207{ 1208 mCameraService = cameraService; 1209 mRemoteBinder = remoteCallback; 1210 mCameraId = cameraId; 1211 mCameraFacing = cameraFacing; 1212 mClientPid = clientPid; 1213 mClientUid = clientUid; 1214 mServicePid = servicePid; 1215 mOpsActive = false; 1216 mDestructionStarted = false; 1217} 1218 1219CameraService::BasicClient::~BasicClient() { 1220 ALOGV("~BasicClient"); 1221 mDestructionStarted = true; 1222} 1223 1224void CameraService::BasicClient::disconnect() { 1225 ALOGV("BasicClient::disconnect"); 1226 mCameraService->removeClientByRemote(mRemoteBinder); 1227 // client shouldn't be able to call into us anymore 1228 mClientPid = 0; 1229} 1230 1231status_t CameraService::BasicClient::startCameraOps() { 1232 int32_t res; 1233 1234 mOpsCallback = new OpsCallback(this); 1235 1236 { 1237 ALOGV("%s: Start camera ops, package name = %s, client UID = %d", 1238 __FUNCTION__, String8(mClientPackageName).string(), mClientUid); 1239 } 1240 1241 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA, 1242 mClientPackageName, mOpsCallback); 1243 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA, 1244 mClientUid, mClientPackageName); 1245 1246 if (res != AppOpsManager::MODE_ALLOWED) { 1247 ALOGI("Camera %d: Access for \"%s\" has been revoked", 1248 mCameraId, String8(mClientPackageName).string()); 1249 return PERMISSION_DENIED; 1250 } 1251 mOpsActive = true; 1252 return OK; 1253} 1254 1255status_t CameraService::BasicClient::finishCameraOps() { 1256 if (mOpsActive) { 1257 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid, 1258 mClientPackageName); 1259 mOpsActive = false; 1260 } 1261 mAppOpsManager.stopWatchingMode(mOpsCallback); 1262 mOpsCallback.clear(); 1263 1264 return OK; 1265} 1266 1267void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) { 1268 String8 name(packageName); 1269 String8 myName(mClientPackageName); 1270 1271 if (op != AppOpsManager::OP_CAMERA) { 1272 ALOGW("Unexpected app ops notification received: %d", op); 1273 return; 1274 } 1275 1276 int32_t res; 1277 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA, 1278 mClientUid, mClientPackageName); 1279 ALOGV("checkOp returns: %d, %s ", res, 1280 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" : 1281 res == AppOpsManager::MODE_IGNORED ? "IGNORED" : 1282 res == AppOpsManager::MODE_ERRORED ? "ERRORED" : 1283 "UNKNOWN"); 1284 1285 if (res != AppOpsManager::MODE_ALLOWED) { 1286 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId, 1287 myName.string()); 1288 // Reset the client PID to allow server-initiated disconnect, 1289 // and to prevent further calls by client. 1290 mClientPid = getCallingPid(); 1291 CaptureResultExtras resultExtras; // a dummy result (invalid) 1292 notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras); 1293 disconnect(); 1294 } 1295} 1296 1297// ---------------------------------------------------------------------------- 1298 1299Mutex* CameraService::Client::getClientLockFromCookie(void* user) { 1300 return gCameraService->getClientLockById((int)(intptr_t) user); 1301} 1302 1303// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should 1304// be acquired for this to be safe 1305CameraService::Client* CameraService::Client::getClientFromCookie(void* user) { 1306 BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int)(intptr_t) user); 1307 // OK: only CameraClient calls this, and they already cast anyway. 1308 Client* client = static_cast<Client*>(basicClient); 1309 1310 // This could happen if the Client is in the process of shutting down (the 1311 // last strong reference is gone, but the destructor hasn't finished 1312 // stopping the hardware). 1313 if (client == NULL) return NULL; 1314 1315 // destruction already started, so should not be accessed 1316 if (client->mDestructionStarted) return NULL; 1317 1318 return client; 1319} 1320 1321void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode, 1322 const CaptureResultExtras& resultExtras) { 1323 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0); 1324} 1325 1326// NOTE: function is idempotent 1327void CameraService::Client::disconnect() { 1328 ALOGV("Client::disconnect"); 1329 BasicClient::disconnect(); 1330 mCameraService->setCameraFree(mCameraId); 1331 1332 StatusVector rejectSourceStates; 1333 rejectSourceStates.push_back(ICameraServiceListener::STATUS_NOT_PRESENT); 1334 rejectSourceStates.push_back(ICameraServiceListener::STATUS_ENUMERATING); 1335 1336 // Transition to PRESENT if the camera is not in either of above 2 states 1337 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT, 1338 mCameraId, 1339 &rejectSourceStates); 1340} 1341 1342CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client): 1343 mClient(client) { 1344} 1345 1346void CameraService::Client::OpsCallback::opChanged(int32_t op, 1347 const String16& packageName) { 1348 sp<BasicClient> client = mClient.promote(); 1349 if (client != NULL) { 1350 client->opChanged(op, packageName); 1351 } 1352} 1353 1354// ---------------------------------------------------------------------------- 1355// IProCamera 1356// ---------------------------------------------------------------------------- 1357 1358CameraService::ProClient::ProClient(const sp<CameraService>& cameraService, 1359 const sp<IProCameraCallbacks>& remoteCallback, 1360 const String16& clientPackageName, 1361 int cameraId, 1362 int cameraFacing, 1363 int clientPid, 1364 uid_t clientUid, 1365 int servicePid) 1366 : CameraService::BasicClient(cameraService, remoteCallback->asBinder(), 1367 clientPackageName, cameraId, cameraFacing, 1368 clientPid, clientUid, servicePid) 1369{ 1370 mRemoteCallback = remoteCallback; 1371} 1372 1373CameraService::ProClient::~ProClient() { 1374} 1375 1376void CameraService::ProClient::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode, 1377 const CaptureResultExtras& resultExtras) { 1378 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0); 1379} 1380 1381// ---------------------------------------------------------------------------- 1382 1383static const int kDumpLockRetries = 50; 1384static const int kDumpLockSleep = 60000; 1385 1386static bool tryLock(Mutex& mutex) 1387{ 1388 bool locked = false; 1389 for (int i = 0; i < kDumpLockRetries; ++i) { 1390 if (mutex.tryLock() == NO_ERROR) { 1391 locked = true; 1392 break; 1393 } 1394 usleep(kDumpLockSleep); 1395 } 1396 return locked; 1397} 1398 1399status_t CameraService::dump(int fd, const Vector<String16>& args) { 1400 String8 result; 1401 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 1402 result.appendFormat("Permission Denial: " 1403 "can't dump CameraService from pid=%d, uid=%d\n", 1404 getCallingPid(), 1405 getCallingUid()); 1406 write(fd, result.string(), result.size()); 1407 } else { 1408 bool locked = tryLock(mServiceLock); 1409 // failed to lock - CameraService is probably deadlocked 1410 if (!locked) { 1411 result.append("CameraService may be deadlocked\n"); 1412 write(fd, result.string(), result.size()); 1413 } 1414 1415 bool hasClient = false; 1416 if (!mModule) { 1417 result = String8::format("No camera module available!\n"); 1418 write(fd, result.string(), result.size()); 1419 if (locked) mServiceLock.unlock(); 1420 return NO_ERROR; 1421 } 1422 1423 result = String8::format("Camera module HAL API version: 0x%x\n", 1424 mModule->common.hal_api_version); 1425 result.appendFormat("Camera module API version: 0x%x\n", 1426 mModule->common.module_api_version); 1427 result.appendFormat("Camera module name: %s\n", 1428 mModule->common.name); 1429 result.appendFormat("Camera module author: %s\n", 1430 mModule->common.author); 1431 result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras); 1432 1433 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor(); 1434 if (desc == NULL) { 1435 result.appendFormat("Vendor tags left unimplemented.\n"); 1436 } else { 1437 result.appendFormat("Vendor tag definitions:\n"); 1438 } 1439 1440 write(fd, result.string(), result.size()); 1441 1442 if (desc != NULL) { 1443 desc->dump(fd, /*verbosity*/2, /*indentation*/4); 1444 } 1445 1446 for (int i = 0; i < mNumberOfCameras; i++) { 1447 result = String8::format("Camera %d static information:\n", i); 1448 camera_info info; 1449 1450 status_t rc = mModule->get_camera_info(i, &info); 1451 if (rc != OK) { 1452 result.appendFormat(" Error reading static information!\n"); 1453 write(fd, result.string(), result.size()); 1454 } else { 1455 result.appendFormat(" Facing: %s\n", 1456 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT"); 1457 result.appendFormat(" Orientation: %d\n", info.orientation); 1458 int deviceVersion; 1459 if (mModule->common.module_api_version < 1460 CAMERA_MODULE_API_VERSION_2_0) { 1461 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 1462 } else { 1463 deviceVersion = info.device_version; 1464 } 1465 result.appendFormat(" Device version: 0x%x\n", deviceVersion); 1466 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) { 1467 result.appendFormat(" Device static metadata:\n"); 1468 write(fd, result.string(), result.size()); 1469 dump_indented_camera_metadata(info.static_camera_characteristics, 1470 fd, /*verbosity*/2, /*indentation*/4); 1471 } else { 1472 write(fd, result.string(), result.size()); 1473 } 1474 } 1475 1476 sp<BasicClient> client = mClient[i].promote(); 1477 if (client == 0) { 1478 result = String8::format(" Device is closed, no client instance\n"); 1479 write(fd, result.string(), result.size()); 1480 continue; 1481 } 1482 hasClient = true; 1483 result = String8::format(" Device is open. Client instance dump:\n"); 1484 write(fd, result.string(), result.size()); 1485 client->dump(fd, args); 1486 } 1487 if (!hasClient) { 1488 result = String8::format("\nNo active camera clients yet.\n"); 1489 write(fd, result.string(), result.size()); 1490 } 1491 1492 if (locked) mServiceLock.unlock(); 1493 1494 // Dump camera traces if there were any 1495 write(fd, "\n", 1); 1496 camera3::CameraTraces::dump(fd, args); 1497 1498 // change logging level 1499 int n = args.size(); 1500 for (int i = 0; i + 1 < n; i++) { 1501 String16 verboseOption("-v"); 1502 if (args[i] == verboseOption) { 1503 String8 levelStr(args[i+1]); 1504 int level = atoi(levelStr.string()); 1505 result = String8::format("\nSetting log level to %d.\n", level); 1506 setLogLevel(level); 1507 write(fd, result.string(), result.size()); 1508 } 1509 } 1510 1511 } 1512 return NO_ERROR; 1513} 1514 1515/*virtual*/void CameraService::binderDied( 1516 const wp<IBinder> &who) { 1517 1518 /** 1519 * While tempting to promote the wp<IBinder> into a sp, 1520 * it's actually not supported by the binder driver 1521 */ 1522 1523 ALOGV("java clients' binder died"); 1524 1525 sp<BasicClient> cameraClient = getClientByRemote(who); 1526 1527 if (cameraClient == 0) { 1528 ALOGV("java clients' binder death already cleaned up (normal case)"); 1529 return; 1530 } 1531 1532 ALOGW("Disconnecting camera client %p since the binder for it " 1533 "died (this pid %d)", cameraClient.get(), getCallingPid()); 1534 1535 cameraClient->disconnect(); 1536 1537} 1538 1539void CameraService::updateStatus(ICameraServiceListener::Status status, 1540 int32_t cameraId, 1541 const StatusVector *rejectSourceStates) { 1542 // do not lock mServiceLock here or can get into a deadlock from 1543 // connect() -> ProClient::disconnect -> updateStatus 1544 Mutex::Autolock lock(mStatusMutex); 1545 1546 ICameraServiceListener::Status oldStatus = mStatusList[cameraId]; 1547 1548 mStatusList[cameraId] = status; 1549 1550 if (oldStatus != status) { 1551 ALOGV("%s: Status has changed for camera ID %d from 0x%x to 0x%x", 1552 __FUNCTION__, cameraId, (uint32_t)oldStatus, (uint32_t)status); 1553 1554 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT && 1555 (status != ICameraServiceListener::STATUS_PRESENT && 1556 status != ICameraServiceListener::STATUS_ENUMERATING)) { 1557 1558 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT" 1559 " or ENUMERATING", __FUNCTION__); 1560 mStatusList[cameraId] = oldStatus; 1561 return; 1562 } 1563 1564 if (rejectSourceStates != NULL) { 1565 const StatusVector &rejectList = *rejectSourceStates; 1566 StatusVector::const_iterator it = rejectList.begin(); 1567 1568 /** 1569 * Sometimes we want to conditionally do a transition. 1570 * For example if a client disconnects, we want to go to PRESENT 1571 * only if we weren't already in NOT_PRESENT or ENUMERATING. 1572 */ 1573 for (; it != rejectList.end(); ++it) { 1574 if (oldStatus == *it) { 1575 ALOGV("%s: Rejecting status transition for Camera ID %d, " 1576 " since the source state was was in one of the bad " 1577 " states.", __FUNCTION__, cameraId); 1578 mStatusList[cameraId] = oldStatus; 1579 return; 1580 } 1581 } 1582 } 1583 1584 /** 1585 * ProClients lose their exclusive lock. 1586 * - Done before the CameraClient can initialize the HAL device, 1587 * since we want to be able to close it before they get to initialize 1588 */ 1589 if (status == ICameraServiceListener::STATUS_NOT_AVAILABLE) { 1590 Vector<wp<ProClient> > proClients(mProClientList[cameraId]); 1591 Vector<wp<ProClient> >::const_iterator it; 1592 1593 for (it = proClients.begin(); it != proClients.end(); ++it) { 1594 sp<ProClient> proCl = it->promote(); 1595 if (proCl.get() != NULL) { 1596 proCl->onExclusiveLockStolen(); 1597 } 1598 } 1599 } 1600 1601 Vector<sp<ICameraServiceListener> >::const_iterator it; 1602 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) { 1603 (*it)->onStatusChanged(status, cameraId); 1604 } 1605 } 1606} 1607 1608ICameraServiceListener::Status CameraService::getStatus(int cameraId) const { 1609 if (cameraId < 0 || cameraId >= MAX_CAMERAS) { 1610 ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId); 1611 return ICameraServiceListener::STATUS_UNKNOWN; 1612 } 1613 1614 Mutex::Autolock al(mStatusMutex); 1615 return mStatusList[cameraId]; 1616} 1617 1618}; // namespace android 1619