1 /* 2 ** 3 ** Copyright (C) 2008, The Android Open Source Project 4 ** 5 ** Licensed under the Apache License, Version 2.0 (the "License"); 6 ** you may not use this file except in compliance with the License. 7 ** You may obtain a copy of the License at 8 ** 9 ** http://www.apache.org/licenses/LICENSE-2.0 10 ** 11 ** Unless required by applicable law or agreed to in writing, software 12 ** distributed under the License is distributed on an "AS IS" BASIS, 13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 ** See the License for the specific language governing permissions and 15 ** limitations under the License. 16 */ 17 18 #define LOG_TAG "CameraService" 19 //#define LOG_NDEBUG 0 20 21 #include <stdio.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/mediaplayer.h> 36 #include <utils/Errors.h> 37 #include <utils/Log.h> 38 #include <utils/String16.h> 39 40 #include "CameraService.h" 41 #include "api1/CameraClient.h" 42 #include "api1/Camera2Client.h" 43 #include "api_pro/ProCamera2Client.h" 44 #include "api2/CameraDeviceClient.h" 45 #include "utils/CameraTraces.h" 46 #include "CameraDeviceFactory.h" 47 48 namespace android { 49 50 // ---------------------------------------------------------------------------- 51 // Logging support -- this is for debugging only 52 // Use "adb shell dumpsys media.camera -v 1" to change it. 53 volatile int32_t gLogLevel = 0; 54 55 #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__); 56 #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__); 57 58 static void setLogLevel(int level) { 59 android_atomic_write(level, &gLogLevel); 60 } 61 62 // ---------------------------------------------------------------------------- 63 64 static int getCallingPid() { 65 return IPCThreadState::self()->getCallingPid(); 66 } 67 68 static int getCallingUid() { 69 return IPCThreadState::self()->getCallingUid(); 70 } 71 72 extern "C" { 73 static void camera_device_status_change( 74 const struct camera_module_callbacks* callbacks, 75 int camera_id, 76 int new_status) { 77 sp<CameraService> cs = const_cast<CameraService*>( 78 static_cast<const CameraService*>(callbacks)); 79 80 cs->onDeviceStatusChanged( 81 camera_id, 82 new_status); 83 } 84 } // extern "C" 85 86 // ---------------------------------------------------------------------------- 87 88 // This is ugly and only safe if we never re-create the CameraService, but 89 // should be ok for now. 90 static CameraService *gCameraService; 91 92 CameraService::CameraService() 93 :mSoundRef(0), mModule(0) 94 { 95 ALOGI("CameraService started (pid=%d)", getpid()); 96 gCameraService = this; 97 98 for (size_t i = 0; i < MAX_CAMERAS; ++i) { 99 mStatusList[i] = ICameraServiceListener::STATUS_PRESENT; 100 } 101 102 this->camera_device_status_change = android::camera_device_status_change; 103 } 104 105 void CameraService::onFirstRef() 106 { 107 LOG1("CameraService::onFirstRef"); 108 109 BnCameraService::onFirstRef(); 110 111 if (hw_get_module(CAMERA_HARDWARE_MODULE_ID, 112 (const hw_module_t **)&mModule) < 0) { 113 ALOGE("Could not load camera HAL module"); 114 mNumberOfCameras = 0; 115 } 116 else { 117 ALOGI("Loaded \"%s\" camera module", mModule->common.name); 118 mNumberOfCameras = mModule->get_number_of_cameras(); 119 if (mNumberOfCameras > MAX_CAMERAS) { 120 ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).", 121 mNumberOfCameras, MAX_CAMERAS); 122 mNumberOfCameras = MAX_CAMERAS; 123 } 124 for (int i = 0; i < mNumberOfCameras; i++) { 125 setCameraFree(i); 126 } 127 128 if (mModule->common.module_api_version >= 129 CAMERA_MODULE_API_VERSION_2_1) { 130 mModule->set_callbacks(this); 131 } 132 133 CameraDeviceFactory::registerService(this); 134 } 135 } 136 137 CameraService::~CameraService() { 138 for (int i = 0; i < mNumberOfCameras; i++) { 139 if (mBusy[i]) { 140 ALOGE("camera %d is still in use in destructor!", i); 141 } 142 } 143 144 gCameraService = NULL; 145 } 146 147 void CameraService::onDeviceStatusChanged(int cameraId, 148 int newStatus) 149 { 150 ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__, 151 cameraId, newStatus); 152 153 if (cameraId < 0 || cameraId >= MAX_CAMERAS) { 154 ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId); 155 return; 156 } 157 158 if ((int)getStatus(cameraId) == newStatus) { 159 ALOGE("%s: State transition to the same status 0x%x not allowed", 160 __FUNCTION__, (uint32_t)newStatus); 161 return; 162 } 163 164 /* don't do this in updateStatus 165 since it is also called from connect and we could get into a deadlock */ 166 if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) { 167 Vector<sp<BasicClient> > clientsToDisconnect; 168 { 169 Mutex::Autolock al(mServiceLock); 170 171 /* Find all clients that we need to disconnect */ 172 sp<BasicClient> client = mClient[cameraId].promote(); 173 if (client.get() != NULL) { 174 clientsToDisconnect.push_back(client); 175 } 176 177 int i = cameraId; 178 for (size_t j = 0; j < mProClientList[i].size(); ++j) { 179 sp<ProClient> cl = mProClientList[i][j].promote(); 180 if (cl != NULL) { 181 clientsToDisconnect.push_back(cl); 182 } 183 } 184 } 185 186 /* now disconnect them. don't hold the lock 187 or we can get into a deadlock */ 188 189 for (size_t i = 0; i < clientsToDisconnect.size(); ++i) { 190 sp<BasicClient> client = clientsToDisconnect[i]; 191 192 client->disconnect(); 193 /** 194 * The remote app will no longer be able to call methods on the 195 * client since the client PID will be reset to 0 196 */ 197 } 198 199 ALOGV("%s: After unplug, disconnected %d clients", 200 __FUNCTION__, clientsToDisconnect.size()); 201 } 202 203 updateStatus( 204 static_cast<ICameraServiceListener::Status>(newStatus), cameraId); 205 206 } 207 208 int32_t CameraService::getNumberOfCameras() { 209 return mNumberOfCameras; 210 } 211 212 status_t CameraService::getCameraInfo(int cameraId, 213 struct CameraInfo* cameraInfo) { 214 if (!mModule) { 215 return -ENODEV; 216 } 217 218 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 219 return BAD_VALUE; 220 } 221 222 struct camera_info info; 223 status_t rc = mModule->get_camera_info(cameraId, &info); 224 cameraInfo->facing = info.facing; 225 cameraInfo->orientation = info.orientation; 226 return rc; 227 } 228 229 status_t CameraService::getCameraCharacteristics(int cameraId, 230 CameraMetadata* cameraInfo) { 231 if (!cameraInfo) { 232 ALOGE("%s: cameraInfo is NULL", __FUNCTION__); 233 return BAD_VALUE; 234 } 235 236 if (!mModule) { 237 ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__); 238 return -ENODEV; 239 } 240 241 if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0) { 242 // TODO: Remove this check once HAL1 shim is in place. 243 ALOGE("%s: Only HAL module version V2 or higher supports static metadata", __FUNCTION__); 244 return BAD_VALUE; 245 } 246 247 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 248 ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId); 249 return BAD_VALUE; 250 } 251 252 int facing; 253 if (getDeviceVersion(cameraId, &facing) == CAMERA_DEVICE_API_VERSION_1_0) { 254 // TODO: Remove this check once HAL1 shim is in place. 255 ALOGE("%s: HAL1 doesn't support static metadata yet", __FUNCTION__); 256 return BAD_VALUE; 257 } 258 259 if (getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1) { 260 // Disable HAL2.x support for camera2 API for now. 261 ALOGW("%s: HAL2.x doesn't support getCameraCharacteristics for now", __FUNCTION__); 262 return BAD_VALUE; 263 } 264 265 struct camera_info info; 266 status_t ret = mModule->get_camera_info(cameraId, &info); 267 *cameraInfo = info.static_camera_characteristics; 268 269 return ret; 270 } 271 272 int CameraService::getDeviceVersion(int cameraId, int* facing) { 273 struct camera_info info; 274 if (mModule->get_camera_info(cameraId, &info) != OK) { 275 return -1; 276 } 277 278 int deviceVersion; 279 if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_0) { 280 deviceVersion = info.device_version; 281 } else { 282 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 283 } 284 285 if (facing) { 286 *facing = info.facing; 287 } 288 289 return deviceVersion; 290 } 291 292 bool CameraService::isValidCameraId(int cameraId) { 293 int facing; 294 int deviceVersion = getDeviceVersion(cameraId, &facing); 295 296 switch(deviceVersion) { 297 case CAMERA_DEVICE_API_VERSION_1_0: 298 case CAMERA_DEVICE_API_VERSION_2_0: 299 case CAMERA_DEVICE_API_VERSION_2_1: 300 case CAMERA_DEVICE_API_VERSION_3_0: 301 return true; 302 default: 303 return false; 304 } 305 306 return false; 307 } 308 309 status_t CameraService::validateConnect(int cameraId, 310 /*inout*/ 311 int& clientUid) const { 312 313 int callingPid = getCallingPid(); 314 315 if (clientUid == USE_CALLING_UID) { 316 clientUid = getCallingUid(); 317 } else { 318 // We only trust our own process to forward client UIDs 319 if (callingPid != getpid()) { 320 ALOGE("CameraService::connect X (pid %d) rejected (don't trust clientUid)", 321 callingPid); 322 return PERMISSION_DENIED; 323 } 324 } 325 326 if (!mModule) { 327 ALOGE("Camera HAL module not loaded"); 328 return -ENODEV; 329 } 330 331 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 332 ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).", 333 callingPid, cameraId); 334 return -ENODEV; 335 } 336 337 char value[PROPERTY_VALUE_MAX]; 338 property_get("sys.secpolicy.camera.disabled", value, "0"); 339 if (strcmp(value, "1") == 0) { 340 // Camera is disabled by DevicePolicyManager. 341 ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid); 342 return -EACCES; 343 } 344 345 ICameraServiceListener::Status currentStatus = getStatus(cameraId); 346 if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) { 347 ALOGI("Camera is not plugged in," 348 " connect X (pid %d) rejected", callingPid); 349 return -ENODEV; 350 } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) { 351 ALOGI("Camera is enumerating," 352 " connect X (pid %d) rejected", callingPid); 353 return -EBUSY; 354 } 355 // Else don't check for STATUS_NOT_AVAILABLE. 356 // -- It's done implicitly in canConnectUnsafe /w the mBusy array 357 358 return OK; 359 } 360 361 bool CameraService::canConnectUnsafe(int cameraId, 362 const String16& clientPackageName, 363 const sp<IBinder>& remoteCallback, 364 sp<BasicClient> &client) { 365 String8 clientName8(clientPackageName); 366 int callingPid = getCallingPid(); 367 368 if (mClient[cameraId] != 0) { 369 client = mClient[cameraId].promote(); 370 if (client != 0) { 371 if (remoteCallback == client->getRemote()) { 372 LOG1("CameraService::connect X (pid %d) (the same client)", 373 callingPid); 374 return true; 375 } else { 376 // TODOSC: need to support 1 regular client, 377 // multiple shared clients here 378 ALOGW("CameraService::connect X (pid %d) rejected" 379 " (existing client).", callingPid); 380 return false; 381 } 382 } 383 mClient[cameraId].clear(); 384 } 385 386 /* 387 mBusy is set to false as the last step of the Client destructor, 388 after which it is guaranteed that the Client destructor has finished ( 389 including any inherited destructors) 390 391 We only need this for a Client subclasses since we don't allow 392 multiple Clents to be opened concurrently, but multiple BasicClient 393 would be fine 394 */ 395 if (mBusy[cameraId]) { 396 ALOGW("CameraService::connect X (pid %d, \"%s\") rejected" 397 " (camera %d is still busy).", callingPid, 398 clientName8.string(), cameraId); 399 return false; 400 } 401 402 return true; 403 } 404 405 status_t CameraService::connect( 406 const sp<ICameraClient>& cameraClient, 407 int cameraId, 408 const String16& clientPackageName, 409 int clientUid, 410 /*out*/ 411 sp<ICamera>& device) { 412 413 String8 clientName8(clientPackageName); 414 int callingPid = getCallingPid(); 415 416 LOG1("CameraService::connect E (pid %d \"%s\", id %d)", callingPid, 417 clientName8.string(), cameraId); 418 419 status_t status = validateConnect(cameraId, /*inout*/clientUid); 420 if (status != OK) { 421 return status; 422 } 423 424 425 sp<Client> client; 426 { 427 Mutex::Autolock lock(mServiceLock); 428 sp<BasicClient> clientTmp; 429 if (!canConnectUnsafe(cameraId, clientPackageName, 430 cameraClient->asBinder(), 431 /*out*/clientTmp)) { 432 return -EBUSY; 433 } else if (client.get() != NULL) { 434 device = static_cast<Client*>(clientTmp.get()); 435 return OK; 436 } 437 438 int facing = -1; 439 int deviceVersion = getDeviceVersion(cameraId, &facing); 440 441 // If there are other non-exclusive users of the camera, 442 // this will tear them down before we can reuse the camera 443 if (isValidCameraId(cameraId)) { 444 // transition from PRESENT -> NOT_AVAILABLE 445 updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE, 446 cameraId); 447 } 448 449 switch(deviceVersion) { 450 case CAMERA_DEVICE_API_VERSION_1_0: 451 client = new CameraClient(this, cameraClient, 452 clientPackageName, cameraId, 453 facing, callingPid, clientUid, getpid()); 454 break; 455 case CAMERA_DEVICE_API_VERSION_2_0: 456 case CAMERA_DEVICE_API_VERSION_2_1: 457 case CAMERA_DEVICE_API_VERSION_3_0: 458 client = new Camera2Client(this, cameraClient, 459 clientPackageName, cameraId, 460 facing, callingPid, clientUid, getpid(), 461 deviceVersion); 462 break; 463 case -1: 464 ALOGE("Invalid camera id %d", cameraId); 465 return BAD_VALUE; 466 default: 467 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 468 return INVALID_OPERATION; 469 } 470 471 status_t status = connectFinishUnsafe(client, client->getRemote()); 472 if (status != OK) { 473 // this is probably not recoverable.. maybe the client can try again 474 // OK: we can only get here if we were originally in PRESENT state 475 updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId); 476 return status; 477 } 478 479 mClient[cameraId] = client; 480 LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, 481 getpid()); 482 } 483 // important: release the mutex here so the client can call back 484 // into the service from its destructor (can be at the end of the call) 485 486 device = client; 487 return OK; 488 } 489 490 status_t CameraService::connectFinishUnsafe(const sp<BasicClient>& client, 491 const sp<IBinder>& remoteCallback) { 492 status_t status = client->initialize(mModule); 493 if (status != OK) { 494 return status; 495 } 496 497 remoteCallback->linkToDeath(this); 498 499 return OK; 500 } 501 502 status_t CameraService::connectPro( 503 const sp<IProCameraCallbacks>& cameraCb, 504 int cameraId, 505 const String16& clientPackageName, 506 int clientUid, 507 /*out*/ 508 sp<IProCameraUser>& device) 509 { 510 String8 clientName8(clientPackageName); 511 int callingPid = getCallingPid(); 512 513 LOG1("CameraService::connectPro E (pid %d \"%s\", id %d)", callingPid, 514 clientName8.string(), cameraId); 515 status_t status = validateConnect(cameraId, /*inout*/clientUid); 516 if (status != OK) { 517 return status; 518 } 519 520 sp<ProClient> client; 521 { 522 Mutex::Autolock lock(mServiceLock); 523 { 524 sp<BasicClient> client; 525 if (!canConnectUnsafe(cameraId, clientPackageName, 526 cameraCb->asBinder(), 527 /*out*/client)) { 528 return -EBUSY; 529 } 530 } 531 532 int facing = -1; 533 int deviceVersion = getDeviceVersion(cameraId, &facing); 534 535 switch(deviceVersion) { 536 case CAMERA_DEVICE_API_VERSION_1_0: 537 ALOGE("Camera id %d uses HALv1, doesn't support ProCamera", 538 cameraId); 539 return -EOPNOTSUPP; 540 break; 541 case CAMERA_DEVICE_API_VERSION_2_0: 542 case CAMERA_DEVICE_API_VERSION_2_1: 543 case CAMERA_DEVICE_API_VERSION_3_0: 544 client = new ProCamera2Client(this, cameraCb, String16(), 545 cameraId, facing, callingPid, USE_CALLING_UID, getpid()); 546 break; 547 case -1: 548 ALOGE("Invalid camera id %d", cameraId); 549 return BAD_VALUE; 550 default: 551 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 552 return INVALID_OPERATION; 553 } 554 555 status_t status = connectFinishUnsafe(client, client->getRemote()); 556 if (status != OK) { 557 return status; 558 } 559 560 mProClientList[cameraId].push(client); 561 562 LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId, 563 getpid()); 564 } 565 // important: release the mutex here so the client can call back 566 // into the service from its destructor (can be at the end of the call) 567 device = client; 568 return OK; 569 } 570 571 status_t CameraService::connectDevice( 572 const sp<ICameraDeviceCallbacks>& cameraCb, 573 int cameraId, 574 const String16& clientPackageName, 575 int clientUid, 576 /*out*/ 577 sp<ICameraDeviceUser>& device) 578 { 579 580 String8 clientName8(clientPackageName); 581 int callingPid = getCallingPid(); 582 583 LOG1("CameraService::connectDevice E (pid %d \"%s\", id %d)", callingPid, 584 clientName8.string(), cameraId); 585 586 status_t status = validateConnect(cameraId, /*inout*/clientUid); 587 if (status != OK) { 588 return status; 589 } 590 591 sp<CameraDeviceClient> client; 592 { 593 Mutex::Autolock lock(mServiceLock); 594 { 595 sp<BasicClient> client; 596 if (!canConnectUnsafe(cameraId, clientPackageName, 597 cameraCb->asBinder(), 598 /*out*/client)) { 599 return -EBUSY; 600 } 601 } 602 603 int facing = -1; 604 int deviceVersion = getDeviceVersion(cameraId, &facing); 605 606 // If there are other non-exclusive users of the camera, 607 // this will tear them down before we can reuse the camera 608 if (isValidCameraId(cameraId)) { 609 // transition from PRESENT -> NOT_AVAILABLE 610 updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE, 611 cameraId); 612 } 613 614 switch(deviceVersion) { 615 case CAMERA_DEVICE_API_VERSION_1_0: 616 ALOGW("Camera using old HAL version: %d", deviceVersion); 617 return -EOPNOTSUPP; 618 // TODO: don't allow 2.0 Only allow 2.1 and higher 619 case CAMERA_DEVICE_API_VERSION_2_0: 620 case CAMERA_DEVICE_API_VERSION_2_1: 621 case CAMERA_DEVICE_API_VERSION_3_0: 622 client = new CameraDeviceClient(this, cameraCb, String16(), 623 cameraId, facing, callingPid, USE_CALLING_UID, getpid()); 624 break; 625 case -1: 626 ALOGE("Invalid camera id %d", cameraId); 627 return BAD_VALUE; 628 default: 629 ALOGE("Unknown camera device HAL version: %d", deviceVersion); 630 return INVALID_OPERATION; 631 } 632 633 status_t status = connectFinishUnsafe(client, client->getRemote()); 634 if (status != OK) { 635 // this is probably not recoverable.. maybe the client can try again 636 // OK: we can only get here if we were originally in PRESENT state 637 updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId); 638 return status; 639 } 640 641 LOG1("CameraService::connectDevice X (id %d, this pid is %d)", cameraId, 642 getpid()); 643 644 mClient[cameraId] = client; 645 } 646 // important: release the mutex here so the client can call back 647 // into the service from its destructor (can be at the end of the call) 648 649 device = client; 650 return OK; 651 } 652 653 654 status_t CameraService::addListener( 655 const sp<ICameraServiceListener>& listener) { 656 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get()); 657 658 Mutex::Autolock lock(mServiceLock); 659 660 Vector<sp<ICameraServiceListener> >::iterator it, end; 661 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) { 662 if ((*it)->asBinder() == listener->asBinder()) { 663 ALOGW("%s: Tried to add listener %p which was already subscribed", 664 __FUNCTION__, listener.get()); 665 return ALREADY_EXISTS; 666 } 667 } 668 669 mListenerList.push_back(listener); 670 671 /* Immediately signal current status to this listener only */ 672 { 673 Mutex::Autolock m(mStatusMutex) ; 674 int numCams = getNumberOfCameras(); 675 for (int i = 0; i < numCams; ++i) { 676 listener->onStatusChanged(mStatusList[i], i); 677 } 678 } 679 680 return OK; 681 } 682 status_t CameraService::removeListener( 683 const sp<ICameraServiceListener>& listener) { 684 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get()); 685 686 Mutex::Autolock lock(mServiceLock); 687 688 Vector<sp<ICameraServiceListener> >::iterator it; 689 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) { 690 if ((*it)->asBinder() == listener->asBinder()) { 691 mListenerList.erase(it); 692 return OK; 693 } 694 } 695 696 ALOGW("%s: Tried to remove a listener %p which was not subscribed", 697 __FUNCTION__, listener.get()); 698 699 return BAD_VALUE; 700 } 701 702 void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) { 703 int callingPid = getCallingPid(); 704 LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid); 705 706 // Declare this before the lock to make absolutely sure the 707 // destructor won't be called with the lock held. 708 Mutex::Autolock lock(mServiceLock); 709 710 int outIndex; 711 sp<BasicClient> client = findClientUnsafe(remoteBinder, outIndex); 712 713 if (client != 0) { 714 // Found our camera, clear and leave. 715 LOG1("removeClient: clear camera %d", outIndex); 716 mClient[outIndex].clear(); 717 718 client->getRemote()->unlinkToDeath(this); 719 } else { 720 721 sp<ProClient> clientPro = findProClientUnsafe(remoteBinder); 722 723 if (clientPro != NULL) { 724 // Found our camera, clear and leave. 725 LOG1("removeClient: clear pro %p", clientPro.get()); 726 727 clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this); 728 } 729 } 730 731 LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid); 732 } 733 734 sp<CameraService::ProClient> CameraService::findProClientUnsafe( 735 const wp<IBinder>& cameraCallbacksRemote) 736 { 737 sp<ProClient> clientPro; 738 739 for (int i = 0; i < mNumberOfCameras; ++i) { 740 Vector<size_t> removeIdx; 741 742 for (size_t j = 0; j < mProClientList[i].size(); ++j) { 743 wp<ProClient> cl = mProClientList[i][j]; 744 745 sp<ProClient> clStrong = cl.promote(); 746 if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) { 747 clientPro = clStrong; 748 break; 749 } else if (clStrong == NULL) { 750 // mark to clean up dead ptr 751 removeIdx.push(j); 752 } 753 } 754 755 // remove stale ptrs (in reverse so the indices dont change) 756 for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) { 757 mProClientList[i].removeAt(removeIdx[j]); 758 } 759 760 } 761 762 return clientPro; 763 } 764 765 sp<CameraService::BasicClient> CameraService::findClientUnsafe( 766 const wp<IBinder>& cameraClient, int& outIndex) { 767 sp<BasicClient> client; 768 769 for (int i = 0; i < mNumberOfCameras; i++) { 770 771 // This happens when we have already disconnected (or this is 772 // just another unused camera). 773 if (mClient[i] == 0) continue; 774 775 // Promote mClient. It can fail if we are called from this path: 776 // Client::~Client() -> disconnect() -> removeClientByRemote(). 777 client = mClient[i].promote(); 778 779 // Clean up stale client entry 780 if (client == NULL) { 781 mClient[i].clear(); 782 continue; 783 } 784 785 if (cameraClient == client->getRemote()) { 786 // Found our camera 787 outIndex = i; 788 return client; 789 } 790 } 791 792 outIndex = -1; 793 return NULL; 794 } 795 796 CameraService::BasicClient* CameraService::getClientByIdUnsafe(int cameraId) { 797 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL; 798 return mClient[cameraId].unsafe_get(); 799 } 800 801 Mutex* CameraService::getClientLockById(int cameraId) { 802 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL; 803 return &mClientLock[cameraId]; 804 } 805 806 sp<CameraService::BasicClient> CameraService::getClientByRemote( 807 const wp<IBinder>& cameraClient) { 808 809 // Declare this before the lock to make absolutely sure the 810 // destructor won't be called with the lock held. 811 sp<BasicClient> client; 812 813 Mutex::Autolock lock(mServiceLock); 814 815 int outIndex; 816 client = findClientUnsafe(cameraClient, outIndex); 817 818 return client; 819 } 820 821 status_t CameraService::onTransact( 822 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { 823 // Permission checks 824 switch (code) { 825 case BnCameraService::CONNECT: 826 case BnCameraService::CONNECT_PRO: 827 const int pid = getCallingPid(); 828 const int self_pid = getpid(); 829 if (pid != self_pid) { 830 // we're called from a different process, do the real check 831 if (!checkCallingPermission( 832 String16("android.permission.CAMERA"))) { 833 const int uid = getCallingUid(); 834 ALOGE("Permission Denial: " 835 "can't use the camera pid=%d, uid=%d", pid, uid); 836 return PERMISSION_DENIED; 837 } 838 } 839 break; 840 } 841 842 return BnCameraService::onTransact(code, data, reply, flags); 843 } 844 845 // The reason we need this busy bit is a new CameraService::connect() request 846 // may come in while the previous Client's destructor has not been run or is 847 // still running. If the last strong reference of the previous Client is gone 848 // but the destructor has not been finished, we should not allow the new Client 849 // to be created because we need to wait for the previous Client to tear down 850 // the hardware first. 851 void CameraService::setCameraBusy(int cameraId) { 852 android_atomic_write(1, &mBusy[cameraId]); 853 854 ALOGV("setCameraBusy cameraId=%d", cameraId); 855 } 856 857 void CameraService::setCameraFree(int cameraId) { 858 android_atomic_write(0, &mBusy[cameraId]); 859 860 ALOGV("setCameraFree cameraId=%d", cameraId); 861 } 862 863 // We share the media players for shutter and recording sound for all clients. 864 // A reference count is kept to determine when we will actually release the 865 // media players. 866 867 MediaPlayer* CameraService::newMediaPlayer(const char *file) { 868 MediaPlayer* mp = new MediaPlayer(); 869 if (mp->setDataSource(file, NULL) == NO_ERROR) { 870 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE); 871 mp->prepare(); 872 } else { 873 ALOGE("Failed to load CameraService sounds: %s", file); 874 return NULL; 875 } 876 return mp; 877 } 878 879 void CameraService::loadSound() { 880 Mutex::Autolock lock(mSoundLock); 881 LOG1("CameraService::loadSound ref=%d", mSoundRef); 882 if (mSoundRef++) return; 883 884 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg"); 885 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg"); 886 } 887 888 void CameraService::releaseSound() { 889 Mutex::Autolock lock(mSoundLock); 890 LOG1("CameraService::releaseSound ref=%d", mSoundRef); 891 if (--mSoundRef) return; 892 893 for (int i = 0; i < NUM_SOUNDS; i++) { 894 if (mSoundPlayer[i] != 0) { 895 mSoundPlayer[i]->disconnect(); 896 mSoundPlayer[i].clear(); 897 } 898 } 899 } 900 901 void CameraService::playSound(sound_kind kind) { 902 LOG1("playSound(%d)", kind); 903 Mutex::Autolock lock(mSoundLock); 904 sp<MediaPlayer> player = mSoundPlayer[kind]; 905 if (player != 0) { 906 player->seekTo(0); 907 player->start(); 908 } 909 } 910 911 // ---------------------------------------------------------------------------- 912 913 CameraService::Client::Client(const sp<CameraService>& cameraService, 914 const sp<ICameraClient>& cameraClient, 915 const String16& clientPackageName, 916 int cameraId, int cameraFacing, 917 int clientPid, uid_t clientUid, 918 int servicePid) : 919 CameraService::BasicClient(cameraService, cameraClient->asBinder(), 920 clientPackageName, 921 cameraId, cameraFacing, 922 clientPid, clientUid, 923 servicePid) 924 { 925 int callingPid = getCallingPid(); 926 LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId); 927 928 mRemoteCallback = cameraClient; 929 930 cameraService->setCameraBusy(cameraId); 931 cameraService->loadSound(); 932 933 LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId); 934 } 935 936 // tear down the client 937 CameraService::Client::~Client() { 938 ALOGV("~Client"); 939 mDestructionStarted = true; 940 941 mCameraService->releaseSound(); 942 // unconditionally disconnect. function is idempotent 943 Client::disconnect(); 944 } 945 946 CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService, 947 const sp<IBinder>& remoteCallback, 948 const String16& clientPackageName, 949 int cameraId, int cameraFacing, 950 int clientPid, uid_t clientUid, 951 int servicePid): 952 mClientPackageName(clientPackageName) 953 { 954 mCameraService = cameraService; 955 mRemoteBinder = remoteCallback; 956 mCameraId = cameraId; 957 mCameraFacing = cameraFacing; 958 mClientPid = clientPid; 959 mClientUid = clientUid; 960 mServicePid = servicePid; 961 mOpsActive = false; 962 mDestructionStarted = false; 963 } 964 965 CameraService::BasicClient::~BasicClient() { 966 ALOGV("~BasicClient"); 967 mDestructionStarted = true; 968 } 969 970 void CameraService::BasicClient::disconnect() { 971 ALOGV("BasicClient::disconnect"); 972 mCameraService->removeClientByRemote(mRemoteBinder); 973 // client shouldn't be able to call into us anymore 974 mClientPid = 0; 975 } 976 977 status_t CameraService::BasicClient::startCameraOps() { 978 int32_t res; 979 980 mOpsCallback = new OpsCallback(this); 981 982 { 983 ALOGV("%s: Start camera ops, package name = %s, client UID = %d", 984 __FUNCTION__, String8(mClientPackageName).string(), mClientUid); 985 } 986 987 mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA, 988 mClientPackageName, mOpsCallback); 989 res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA, 990 mClientUid, mClientPackageName); 991 992 if (res != AppOpsManager::MODE_ALLOWED) { 993 ALOGI("Camera %d: Access for \"%s\" has been revoked", 994 mCameraId, String8(mClientPackageName).string()); 995 return PERMISSION_DENIED; 996 } 997 mOpsActive = true; 998 return OK; 999 } 1000 1001 status_t CameraService::BasicClient::finishCameraOps() { 1002 if (mOpsActive) { 1003 mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid, 1004 mClientPackageName); 1005 mOpsActive = false; 1006 } 1007 mAppOpsManager.stopWatchingMode(mOpsCallback); 1008 mOpsCallback.clear(); 1009 1010 return OK; 1011 } 1012 1013 void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) { 1014 String8 name(packageName); 1015 String8 myName(mClientPackageName); 1016 1017 if (op != AppOpsManager::OP_CAMERA) { 1018 ALOGW("Unexpected app ops notification received: %d", op); 1019 return; 1020 } 1021 1022 int32_t res; 1023 res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA, 1024 mClientUid, mClientPackageName); 1025 ALOGV("checkOp returns: %d, %s ", res, 1026 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" : 1027 res == AppOpsManager::MODE_IGNORED ? "IGNORED" : 1028 res == AppOpsManager::MODE_ERRORED ? "ERRORED" : 1029 "UNKNOWN"); 1030 1031 if (res != AppOpsManager::MODE_ALLOWED) { 1032 ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId, 1033 myName.string()); 1034 // Reset the client PID to allow server-initiated disconnect, 1035 // and to prevent further calls by client. 1036 mClientPid = getCallingPid(); 1037 notifyError(); 1038 disconnect(); 1039 } 1040 } 1041 1042 // ---------------------------------------------------------------------------- 1043 1044 Mutex* CameraService::Client::getClientLockFromCookie(void* user) { 1045 return gCameraService->getClientLockById((int) user); 1046 } 1047 1048 // Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should 1049 // be acquired for this to be safe 1050 CameraService::Client* CameraService::Client::getClientFromCookie(void* user) { 1051 BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int) user); 1052 // OK: only CameraClient calls this, and they already cast anyway. 1053 Client* client = static_cast<Client*>(basicClient); 1054 1055 // This could happen if the Client is in the process of shutting down (the 1056 // last strong reference is gone, but the destructor hasn't finished 1057 // stopping the hardware). 1058 if (client == NULL) return NULL; 1059 1060 // destruction already started, so should not be accessed 1061 if (client->mDestructionStarted) return NULL; 1062 1063 return client; 1064 } 1065 1066 void CameraService::Client::notifyError() { 1067 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0); 1068 } 1069 1070 // NOTE: function is idempotent 1071 void CameraService::Client::disconnect() { 1072 ALOGV("Client::disconnect"); 1073 BasicClient::disconnect(); 1074 mCameraService->setCameraFree(mCameraId); 1075 1076 StatusVector rejectSourceStates; 1077 rejectSourceStates.push_back(ICameraServiceListener::STATUS_NOT_PRESENT); 1078 rejectSourceStates.push_back(ICameraServiceListener::STATUS_ENUMERATING); 1079 1080 // Transition to PRESENT if the camera is not in either of above 2 states 1081 mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT, 1082 mCameraId, 1083 &rejectSourceStates); 1084 } 1085 1086 CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client): 1087 mClient(client) { 1088 } 1089 1090 void CameraService::Client::OpsCallback::opChanged(int32_t op, 1091 const String16& packageName) { 1092 sp<BasicClient> client = mClient.promote(); 1093 if (client != NULL) { 1094 client->opChanged(op, packageName); 1095 } 1096 } 1097 1098 // ---------------------------------------------------------------------------- 1099 // IProCamera 1100 // ---------------------------------------------------------------------------- 1101 1102 CameraService::ProClient::ProClient(const sp<CameraService>& cameraService, 1103 const sp<IProCameraCallbacks>& remoteCallback, 1104 const String16& clientPackageName, 1105 int cameraId, 1106 int cameraFacing, 1107 int clientPid, 1108 uid_t clientUid, 1109 int servicePid) 1110 : CameraService::BasicClient(cameraService, remoteCallback->asBinder(), 1111 clientPackageName, cameraId, cameraFacing, 1112 clientPid, clientUid, servicePid) 1113 { 1114 mRemoteCallback = remoteCallback; 1115 } 1116 1117 CameraService::ProClient::~ProClient() { 1118 } 1119 1120 void CameraService::ProClient::notifyError() { 1121 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0); 1122 } 1123 1124 // ---------------------------------------------------------------------------- 1125 1126 static const int kDumpLockRetries = 50; 1127 static const int kDumpLockSleep = 60000; 1128 1129 static bool tryLock(Mutex& mutex) 1130 { 1131 bool locked = false; 1132 for (int i = 0; i < kDumpLockRetries; ++i) { 1133 if (mutex.tryLock() == NO_ERROR) { 1134 locked = true; 1135 break; 1136 } 1137 usleep(kDumpLockSleep); 1138 } 1139 return locked; 1140 } 1141 1142 status_t CameraService::dump(int fd, const Vector<String16>& args) { 1143 String8 result; 1144 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 1145 result.appendFormat("Permission Denial: " 1146 "can't dump CameraService from pid=%d, uid=%d\n", 1147 getCallingPid(), 1148 getCallingUid()); 1149 write(fd, result.string(), result.size()); 1150 } else { 1151 bool locked = tryLock(mServiceLock); 1152 // failed to lock - CameraService is probably deadlocked 1153 if (!locked) { 1154 result.append("CameraService may be deadlocked\n"); 1155 write(fd, result.string(), result.size()); 1156 } 1157 1158 bool hasClient = false; 1159 if (!mModule) { 1160 result = String8::format("No camera module available!\n"); 1161 write(fd, result.string(), result.size()); 1162 return NO_ERROR; 1163 } 1164 1165 result = String8::format("Camera module HAL API version: 0x%x\n", 1166 mModule->common.hal_api_version); 1167 result.appendFormat("Camera module API version: 0x%x\n", 1168 mModule->common.module_api_version); 1169 result.appendFormat("Camera module name: %s\n", 1170 mModule->common.name); 1171 result.appendFormat("Camera module author: %s\n", 1172 mModule->common.author); 1173 result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras); 1174 write(fd, result.string(), result.size()); 1175 for (int i = 0; i < mNumberOfCameras; i++) { 1176 result = String8::format("Camera %d static information:\n", i); 1177 camera_info info; 1178 1179 status_t rc = mModule->get_camera_info(i, &info); 1180 if (rc != OK) { 1181 result.appendFormat(" Error reading static information!\n"); 1182 write(fd, result.string(), result.size()); 1183 } else { 1184 result.appendFormat(" Facing: %s\n", 1185 info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT"); 1186 result.appendFormat(" Orientation: %d\n", info.orientation); 1187 int deviceVersion; 1188 if (mModule->common.module_api_version < 1189 CAMERA_MODULE_API_VERSION_2_0) { 1190 deviceVersion = CAMERA_DEVICE_API_VERSION_1_0; 1191 } else { 1192 deviceVersion = info.device_version; 1193 } 1194 result.appendFormat(" Device version: 0x%x\n", deviceVersion); 1195 if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) { 1196 result.appendFormat(" Device static metadata:\n"); 1197 write(fd, result.string(), result.size()); 1198 dump_indented_camera_metadata(info.static_camera_characteristics, 1199 fd, 2, 4); 1200 } else { 1201 write(fd, result.string(), result.size()); 1202 } 1203 } 1204 1205 sp<BasicClient> client = mClient[i].promote(); 1206 if (client == 0) { 1207 result = String8::format(" Device is closed, no client instance\n"); 1208 write(fd, result.string(), result.size()); 1209 continue; 1210 } 1211 hasClient = true; 1212 result = String8::format(" Device is open. Client instance dump:\n"); 1213 write(fd, result.string(), result.size()); 1214 client->dump(fd, args); 1215 } 1216 if (!hasClient) { 1217 result = String8::format("\nNo active camera clients yet.\n"); 1218 write(fd, result.string(), result.size()); 1219 } 1220 1221 if (locked) mServiceLock.unlock(); 1222 1223 // Dump camera traces if there were any 1224 write(fd, "\n", 1); 1225 camera3::CameraTraces::dump(fd, args); 1226 1227 // change logging level 1228 int n = args.size(); 1229 for (int i = 0; i + 1 < n; i++) { 1230 String16 verboseOption("-v"); 1231 if (args[i] == verboseOption) { 1232 String8 levelStr(args[i+1]); 1233 int level = atoi(levelStr.string()); 1234 result = String8::format("\nSetting log level to %d.\n", level); 1235 setLogLevel(level); 1236 write(fd, result.string(), result.size()); 1237 } 1238 } 1239 1240 } 1241 return NO_ERROR; 1242 } 1243 1244 /*virtual*/void CameraService::binderDied( 1245 const wp<IBinder> &who) { 1246 1247 /** 1248 * While tempting to promote the wp<IBinder> into a sp, 1249 * it's actually not supported by the binder driver 1250 */ 1251 1252 ALOGV("java clients' binder died"); 1253 1254 sp<BasicClient> cameraClient = getClientByRemote(who); 1255 1256 if (cameraClient == 0) { 1257 ALOGV("java clients' binder death already cleaned up (normal case)"); 1258 return; 1259 } 1260 1261 ALOGW("Disconnecting camera client %p since the binder for it " 1262 "died (this pid %d)", cameraClient.get(), getCallingPid()); 1263 1264 cameraClient->disconnect(); 1265 1266 } 1267 1268 void CameraService::updateStatus(ICameraServiceListener::Status status, 1269 int32_t cameraId, 1270 const StatusVector *rejectSourceStates) { 1271 // do not lock mServiceLock here or can get into a deadlock from 1272 // connect() -> ProClient::disconnect -> updateStatus 1273 Mutex::Autolock lock(mStatusMutex); 1274 1275 ICameraServiceListener::Status oldStatus = mStatusList[cameraId]; 1276 1277 mStatusList[cameraId] = status; 1278 1279 if (oldStatus != status) { 1280 ALOGV("%s: Status has changed for camera ID %d from 0x%x to 0x%x", 1281 __FUNCTION__, cameraId, (uint32_t)oldStatus, (uint32_t)status); 1282 1283 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT && 1284 (status != ICameraServiceListener::STATUS_PRESENT && 1285 status != ICameraServiceListener::STATUS_ENUMERATING)) { 1286 1287 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT" 1288 " or ENUMERATING", __FUNCTION__); 1289 mStatusList[cameraId] = oldStatus; 1290 return; 1291 } 1292 1293 if (rejectSourceStates != NULL) { 1294 const StatusVector &rejectList = *rejectSourceStates; 1295 StatusVector::const_iterator it = rejectList.begin(); 1296 1297 /** 1298 * Sometimes we want to conditionally do a transition. 1299 * For example if a client disconnects, we want to go to PRESENT 1300 * only if we weren't already in NOT_PRESENT or ENUMERATING. 1301 */ 1302 for (; it != rejectList.end(); ++it) { 1303 if (oldStatus == *it) { 1304 ALOGV("%s: Rejecting status transition for Camera ID %d, " 1305 " since the source state was was in one of the bad " 1306 " states.", __FUNCTION__, cameraId); 1307 mStatusList[cameraId] = oldStatus; 1308 return; 1309 } 1310 } 1311 } 1312 1313 /** 1314 * ProClients lose their exclusive lock. 1315 * - Done before the CameraClient can initialize the HAL device, 1316 * since we want to be able to close it before they get to initialize 1317 */ 1318 if (status == ICameraServiceListener::STATUS_NOT_AVAILABLE) { 1319 Vector<wp<ProClient> > proClients(mProClientList[cameraId]); 1320 Vector<wp<ProClient> >::const_iterator it; 1321 1322 for (it = proClients.begin(); it != proClients.end(); ++it) { 1323 sp<ProClient> proCl = it->promote(); 1324 if (proCl.get() != NULL) { 1325 proCl->onExclusiveLockStolen(); 1326 } 1327 } 1328 } 1329 1330 Vector<sp<ICameraServiceListener> >::const_iterator it; 1331 for (it = mListenerList.begin(); it != mListenerList.end(); ++it) { 1332 (*it)->onStatusChanged(status, cameraId); 1333 } 1334 } 1335 } 1336 1337 ICameraServiceListener::Status CameraService::getStatus(int cameraId) const { 1338 if (cameraId < 0 || cameraId >= MAX_CAMERAS) { 1339 ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId); 1340 return ICameraServiceListener::STATUS_UNKNOWN; 1341 } 1342 1343 Mutex::Autolock al(mStatusMutex); 1344 return mStatusList[cameraId]; 1345 } 1346 1347 }; // namespace android 1348