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