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