CameraService.cpp revision 4b79168835965cf0fc41ebe2a367e22b4cb20d08
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 20#include <stdio.h> 21#include <sys/types.h> 22#include <pthread.h> 23 24#include <binder/IPCThreadState.h> 25#include <binder/IServiceManager.h> 26#include <binder/MemoryBase.h> 27#include <binder/MemoryHeapBase.h> 28#include <cutils/atomic.h> 29#include <hardware/hardware.h> 30#include <media/AudioSystem.h> 31#include <media/mediaplayer.h> 32#include <surfaceflinger/ISurface.h> 33#include <ui/Overlay.h> 34#include <utils/Errors.h> 35#include <utils/Log.h> 36#include <utils/String16.h> 37 38#include "CameraService.h" 39 40namespace android { 41 42// ---------------------------------------------------------------------------- 43// Logging support -- this is for debugging only 44// Use "adb shell dumpsys media.camera -v 1" to change it. 45static volatile int32_t gLogLevel = 0; 46 47#define LOG1(...) LOGD_IF(gLogLevel >= 1, __VA_ARGS__); 48#define LOG2(...) LOGD_IF(gLogLevel >= 2, __VA_ARGS__); 49 50static void setLogLevel(int level) { 51 android_atomic_write(level, &gLogLevel); 52} 53 54// ---------------------------------------------------------------------------- 55 56static int getCallingPid() { 57 return IPCThreadState::self()->getCallingPid(); 58} 59 60static int getCallingUid() { 61 return IPCThreadState::self()->getCallingUid(); 62} 63 64// ---------------------------------------------------------------------------- 65 66// This is ugly and only safe if we never re-create the CameraService, but 67// should be ok for now. 68static CameraService *gCameraService; 69 70CameraService::CameraService() 71:mSoundRef(0) 72{ 73 LOGI("CameraService started (pid=%d)", getpid()); 74 75 mNumberOfCameras = HAL_getNumberOfCameras(); 76 if (mNumberOfCameras > MAX_CAMERAS) { 77 LOGE("Number of cameras(%d) > MAX_CAMERAS(%d).", 78 mNumberOfCameras, MAX_CAMERAS); 79 mNumberOfCameras = MAX_CAMERAS; 80 } 81 82 for (int i = 0; i < mNumberOfCameras; i++) { 83 setCameraFree(i); 84 } 85 86 gCameraService = this; 87} 88 89CameraService::~CameraService() { 90 for (int i = 0; i < mNumberOfCameras; i++) { 91 if (mBusy[i]) { 92 LOGE("camera %d is still in use in destructor!", i); 93 } 94 } 95 96 gCameraService = NULL; 97} 98 99int32_t CameraService::getNumberOfCameras() { 100 return mNumberOfCameras; 101} 102 103status_t CameraService::getCameraInfo(int cameraId, 104 struct CameraInfo* cameraInfo) { 105 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 106 return BAD_VALUE; 107 } 108 109 HAL_getCameraInfo(cameraId, cameraInfo); 110 return OK; 111} 112 113sp<ICamera> CameraService::connect( 114 const sp<ICameraClient>& cameraClient, int cameraId) { 115 int callingPid = getCallingPid(); 116 LOG1("CameraService::connect E (pid %d, id %d)", callingPid, cameraId); 117 118 sp<Client> client; 119 if (cameraId < 0 || cameraId >= mNumberOfCameras) { 120 LOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).", 121 callingPid, cameraId); 122 return NULL; 123 } 124 125 Mutex::Autolock lock(mServiceLock); 126 if (mClient[cameraId] != 0) { 127 client = mClient[cameraId].promote(); 128 if (client != 0) { 129 if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) { 130 LOG1("CameraService::connect X (pid %d) (the same client)", 131 callingPid); 132 return client; 133 } else { 134 LOGW("CameraService::connect X (pid %d) rejected (existing client).", 135 callingPid); 136 return NULL; 137 } 138 } 139 mClient[cameraId].clear(); 140 } 141 142 if (mBusy[cameraId]) { 143 LOGW("CameraService::connect X (pid %d) rejected" 144 " (camera %d is still busy).", callingPid, cameraId); 145 return NULL; 146 } 147 148 sp<CameraHardwareInterface> hardware = HAL_openCameraHardware(cameraId); 149 if (hardware == NULL) { 150 LOGE("Fail to open camera hardware (id=%d)", cameraId); 151 return NULL; 152 } 153 client = new Client(this, cameraClient, hardware, cameraId, callingPid); 154 mClient[cameraId] = client; 155 LOG1("CameraService::connect X"); 156 return client; 157} 158 159void CameraService::removeClient(const sp<ICameraClient>& cameraClient) { 160 int callingPid = getCallingPid(); 161 LOG1("CameraService::removeClient E (pid %d)", callingPid); 162 163 for (int i = 0; i < mNumberOfCameras; i++) { 164 // Declare this before the lock to make absolutely sure the 165 // destructor won't be called with the lock held. 166 sp<Client> client; 167 168 Mutex::Autolock lock(mServiceLock); 169 170 // This happens when we have already disconnected (or this is 171 // just another unused camera). 172 if (mClient[i] == 0) continue; 173 174 // Promote mClient. It can fail if we are called from this path: 175 // Client::~Client() -> disconnect() -> removeClient(). 176 client = mClient[i].promote(); 177 178 if (client == 0) { 179 mClient[i].clear(); 180 continue; 181 } 182 183 if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) { 184 // Found our camera, clear and leave. 185 LOG1("removeClient: clear camera %d", i); 186 mClient[i].clear(); 187 break; 188 } 189 } 190 191 LOG1("CameraService::removeClient X (pid %d)", callingPid); 192} 193 194sp<CameraService::Client> CameraService::getClientById(int cameraId) { 195 if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL; 196 return mClient[cameraId].promote(); 197} 198 199status_t CameraService::onTransact( 200 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { 201 // Permission checks 202 switch (code) { 203 case BnCameraService::CONNECT: 204 const int pid = getCallingPid(); 205 const int self_pid = getpid(); 206 if (pid != self_pid) { 207 // we're called from a different process, do the real check 208 if (!checkCallingPermission( 209 String16("android.permission.CAMERA"))) { 210 const int uid = getCallingUid(); 211 LOGE("Permission Denial: " 212 "can't use the camera pid=%d, uid=%d", pid, uid); 213 return PERMISSION_DENIED; 214 } 215 } 216 break; 217 } 218 219 return BnCameraService::onTransact(code, data, reply, flags); 220} 221 222// The reason we need this busy bit is a new CameraService::connect() request 223// may come in while the previous Client's destructor has not been run or is 224// still running. If the last strong reference of the previous Client is gone 225// but the destructor has not been finished, we should not allow the new Client 226// to be created because we need to wait for the previous Client to tear down 227// the hardware first. 228void CameraService::setCameraBusy(int cameraId) { 229 android_atomic_write(1, &mBusy[cameraId]); 230} 231 232void CameraService::setCameraFree(int cameraId) { 233 android_atomic_write(0, &mBusy[cameraId]); 234} 235 236// We share the media players for shutter and recording sound for all clients. 237// A reference count is kept to determine when we will actually release the 238// media players. 239 240static MediaPlayer* newMediaPlayer(const char *file) { 241 MediaPlayer* mp = new MediaPlayer(); 242 if (mp->setDataSource(file, NULL) == NO_ERROR) { 243 mp->setAudioStreamType(AudioSystem::ENFORCED_AUDIBLE); 244 mp->prepare(); 245 } else { 246 LOGE("Failed to load CameraService sounds: %s", file); 247 return NULL; 248 } 249 return mp; 250} 251 252void CameraService::loadSound() { 253 Mutex::Autolock lock(mSoundLock); 254 LOG1("CameraService::loadSound ref=%d", mSoundRef); 255 if (mSoundRef++) return; 256 257 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg"); 258 mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg"); 259} 260 261void CameraService::releaseSound() { 262 Mutex::Autolock lock(mSoundLock); 263 LOG1("CameraService::releaseSound ref=%d", mSoundRef); 264 if (--mSoundRef) return; 265 266 for (int i = 0; i < NUM_SOUNDS; i++) { 267 if (mSoundPlayer[i] != 0) { 268 mSoundPlayer[i]->disconnect(); 269 mSoundPlayer[i].clear(); 270 } 271 } 272} 273 274void CameraService::playSound(sound_kind kind) { 275 LOG1("playSound(%d)", kind); 276 Mutex::Autolock lock(mSoundLock); 277 sp<MediaPlayer> player = mSoundPlayer[kind]; 278 if (player != 0) { 279 // do not play the sound if stream volume is 0 280 // (typically because ringer mode is silent). 281 int index; 282 AudioSystem::getStreamVolumeIndex(AudioSystem::ENFORCED_AUDIBLE, &index); 283 if (index != 0) { 284 player->seekTo(0); 285 player->start(); 286 } 287 } 288} 289 290// ---------------------------------------------------------------------------- 291 292CameraService::Client::Client(const sp<CameraService>& cameraService, 293 const sp<ICameraClient>& cameraClient, 294 const sp<CameraHardwareInterface>& hardware, 295 int cameraId, int clientPid) { 296 int callingPid = getCallingPid(); 297 LOG1("Client::Client E (pid %d)", callingPid); 298 299 mCameraService = cameraService; 300 mCameraClient = cameraClient; 301 mHardware = hardware; 302 mCameraId = cameraId; 303 mClientPid = clientPid; 304 mUseOverlay = mHardware->useOverlay(); 305 mMsgEnabled = 0; 306 307 mHardware->setCallbacks(notifyCallback, 308 dataCallback, 309 dataCallbackTimestamp, 310 (void *)cameraId); 311 312 // Enable zoom, error, and focus messages by default 313 enableMsgType(CAMERA_MSG_ERROR | 314 CAMERA_MSG_ZOOM | 315 CAMERA_MSG_FOCUS); 316 mOverlayW = 0; 317 mOverlayH = 0; 318 319 // Callback is disabled by default 320 mPreviewCallbackFlag = FRAME_CALLBACK_FLAG_NOOP; 321 mOrientation = 0; 322 cameraService->setCameraBusy(cameraId); 323 cameraService->loadSound(); 324 LOG1("Client::Client X (pid %d)", callingPid); 325} 326 327static void *unregister_surface(void *arg) { 328 ISurface *surface = (ISurface *)arg; 329 surface->unregisterBuffers(); 330 IPCThreadState::self()->flushCommands(); 331 return NULL; 332} 333 334// tear down the client 335CameraService::Client::~Client() { 336 int callingPid = getCallingPid(); 337 LOG1("Client::~Client E (pid %d, this %p)", callingPid, this); 338 339 // Clean up the ANativeWindow 340 if (mSurface != 0) { 341 setPreviewDisplay(0); 342 } 343 344 // set mClientPid to let disconnet() tear down the hardware 345 mClientPid = callingPid; 346 disconnect(); 347 mCameraService->releaseSound(); 348 LOG1("Client::~Client X (pid %d, this %p)", callingPid, this); 349} 350 351// ---------------------------------------------------------------------------- 352 353status_t CameraService::Client::checkPid() const { 354 int callingPid = getCallingPid(); 355 if (callingPid == mClientPid) return NO_ERROR; 356 357 LOGW("attempt to use a locked camera from a different process" 358 " (old pid %d, new pid %d)", mClientPid, callingPid); 359 return EBUSY; 360} 361 362status_t CameraService::Client::checkPidAndHardware() const { 363 status_t result = checkPid(); 364 if (result != NO_ERROR) return result; 365 if (mHardware == 0) { 366 LOGE("attempt to use a camera after disconnect() (pid %d)", getCallingPid()); 367 return INVALID_OPERATION; 368 } 369 return NO_ERROR; 370} 371 372status_t CameraService::Client::lock() { 373 int callingPid = getCallingPid(); 374 LOG1("lock (pid %d)", callingPid); 375 Mutex::Autolock lock(mLock); 376 377 // lock camera to this client if the the camera is unlocked 378 if (mClientPid == 0) { 379 mClientPid = callingPid; 380 return NO_ERROR; 381 } 382 383 // returns NO_ERROR if the client already owns the camera, EBUSY otherwise 384 return checkPid(); 385} 386 387status_t CameraService::Client::unlock() { 388 int callingPid = getCallingPid(); 389 LOG1("unlock (pid %d)", callingPid); 390 Mutex::Autolock lock(mLock); 391 392 // allow anyone to use camera (after they lock the camera) 393 status_t result = checkPid(); 394 if (result == NO_ERROR) { 395 mClientPid = 0; 396 LOG1("clear mCameraClient (pid %d)", callingPid); 397 // we need to remove the reference to ICameraClient so that when the app 398 // goes away, the reference count goes to 0. 399 mCameraClient.clear(); 400 } 401 return result; 402} 403 404// connect a new client to the camera 405status_t CameraService::Client::connect(const sp<ICameraClient>& client) { 406 int callingPid = getCallingPid(); 407 LOG1("connect E (pid %d)", callingPid); 408 Mutex::Autolock lock(mLock); 409 410 if (mClientPid != 0 && checkPid() != NO_ERROR) { 411 LOGW("Tried to connect to a locked camera (old pid %d, new pid %d)", 412 mClientPid, callingPid); 413 return EBUSY; 414 } 415 416 if (mCameraClient != 0 && (client->asBinder() == mCameraClient->asBinder())) { 417 LOG1("Connect to the same client"); 418 return NO_ERROR; 419 } 420 421 mPreviewCallbackFlag = FRAME_CALLBACK_FLAG_NOOP; 422 mClientPid = callingPid; 423 mCameraClient = client; 424 425 LOG1("connect X (pid %d)", callingPid); 426 return NO_ERROR; 427} 428 429void CameraService::Client::disconnect() { 430 int callingPid = getCallingPid(); 431 LOG1("disconnect E (pid %d)", callingPid); 432 Mutex::Autolock lock(mLock); 433 434 if (checkPid() != NO_ERROR) { 435 LOGW("different client - don't disconnect"); 436 return; 437 } 438 439 if (mClientPid <= 0) { 440 LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid); 441 return; 442 } 443 444 // Make sure disconnect() is done once and once only, whether it is called 445 // from the user directly, or called by the destructor. 446 if (mHardware == 0) return; 447 448 LOG1("hardware teardown"); 449 // Before destroying mHardware, we must make sure it's in the 450 // idle state. 451 // Turn off all messages. 452 disableMsgType(CAMERA_MSG_ALL_MSGS); 453 mHardware->stopPreview(); 454 mHardware->cancelPicture(); 455 // Release the hardware resources. 456 mHardware->release(); 457 // Release the held overlay resources. 458 if (mUseOverlay) { 459 mOverlayRef = 0; 460 } 461 // Release the held ANativeWindow resources. 462 if (mPreviewWindow != 0) { 463 mPreviewWindow = 0; 464 mHardware->setPreviewWindow(mPreviewWindow); 465 } 466 mHardware.clear(); 467 468 mCameraService->removeClient(mCameraClient); 469 mCameraService->setCameraFree(mCameraId); 470 471 LOG1("disconnect X (pid %d)", callingPid); 472} 473 474// ---------------------------------------------------------------------------- 475 476// set the Surface that the preview will use 477status_t CameraService::Client::setPreviewDisplay(const sp<Surface>& surface) { 478 LOG1("setPreviewDisplay(%p) (pid %d)", surface.get(), getCallingPid()); 479 Mutex::Autolock lock(mLock); 480 status_t result = checkPidAndHardware(); 481 if (result != NO_ERROR) return result; 482 483 result = NO_ERROR; 484 485 // return if no change in surface. 486 // asBinder() is safe on NULL (returns NULL) 487 if (getISurface(surface)->asBinder() == mSurface->asBinder()) { 488 return result; 489 } 490 491 if (mSurface != 0) { 492 LOG1("clearing old preview surface %p", mSurface.get()); 493 if (mUseOverlay) { 494 // Force the destruction of any previous overlay 495 sp<Overlay> dummy; 496 mHardware->setOverlay(dummy); 497 } 498 } 499 if (surface != 0) { 500 mSurface = getISurface(surface); 501 } else { 502 mSurface = 0; 503 } 504 mPreviewWindow = surface; 505 mOverlayRef = 0; 506 // If preview has been already started, set overlay or register preview 507 // buffers now. 508 if (mHardware->previewEnabled()) { 509 if (mUseOverlay) { 510 result = setOverlay(); 511 } else if (mPreviewWindow != 0) { 512 result = mHardware->setPreviewWindow(mPreviewWindow); 513 } 514 } 515 516 return result; 517} 518 519status_t CameraService::Client::setOverlay() { 520 int w, h; 521 CameraParameters params(mHardware->getParameters()); 522 params.getPreviewSize(&w, &h); 523 524 if (w != mOverlayW || h != mOverlayH) { 525 // Force the destruction of any previous overlay 526 sp<Overlay> dummy; 527 mHardware->setOverlay(dummy); 528 mOverlayRef = 0; 529 } 530 531 status_t result = NO_ERROR; 532 if (mSurface == 0) { 533 result = mHardware->setOverlay(NULL); 534 } else { 535 if (mOverlayRef == 0) { 536 // FIXME: 537 // Surfaceflinger may hold onto the previous overlay reference for some 538 // time after we try to destroy it. retry a few times. In the future, we 539 // should make the destroy call block, or possibly specify that we can 540 // wait in the createOverlay call if the previous overlay is in the 541 // process of being destroyed. 542 for (int retry = 0; retry < 50; ++retry) { 543 mOverlayRef = mSurface->createOverlay(w, h, OVERLAY_FORMAT_DEFAULT, 544 mOrientation); 545 if (mOverlayRef != 0) break; 546 LOGW("Overlay create failed - retrying"); 547 usleep(20000); 548 } 549 if (mOverlayRef == 0) { 550 LOGE("Overlay Creation Failed!"); 551 return -EINVAL; 552 } 553 result = mHardware->setOverlay(new Overlay(mOverlayRef)); 554 } 555 } 556 if (result != NO_ERROR) { 557 LOGE("mHardware->setOverlay() failed with status %d\n", result); 558 return result; 559 } 560 561 mOverlayW = w; 562 mOverlayH = h; 563 564 return result; 565} 566 567// set the preview callback flag to affect how the received frames from 568// preview are handled. 569void CameraService::Client::setPreviewCallbackFlag(int callback_flag) { 570 LOG1("setPreviewCallbackFlag(%d) (pid %d)", callback_flag, getCallingPid()); 571 Mutex::Autolock lock(mLock); 572 if (checkPidAndHardware() != NO_ERROR) return; 573 574 mPreviewCallbackFlag = callback_flag; 575 576 // If we don't use overlay, we always need the preview frame for display. 577 // If we do use overlay, we only need the preview frame if the user 578 // wants the data. 579 if (mUseOverlay) { 580 if(mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ENABLE_MASK) { 581 enableMsgType(CAMERA_MSG_PREVIEW_FRAME); 582 } else { 583 disableMsgType(CAMERA_MSG_PREVIEW_FRAME); 584 } 585 } 586} 587 588// start preview mode 589status_t CameraService::Client::startPreview() { 590 LOG1("startPreview (pid %d)", getCallingPid()); 591 return startCameraMode(CAMERA_PREVIEW_MODE); 592} 593 594// start recording mode 595status_t CameraService::Client::startRecording() { 596 LOG1("startRecording (pid %d)", getCallingPid()); 597 return startCameraMode(CAMERA_RECORDING_MODE); 598} 599 600// start preview or recording 601status_t CameraService::Client::startCameraMode(camera_mode mode) { 602 LOG1("startCameraMode(%d)", mode); 603 Mutex::Autolock lock(mLock); 604 status_t result = checkPidAndHardware(); 605 if (result != NO_ERROR) return result; 606 607 switch(mode) { 608 case CAMERA_PREVIEW_MODE: 609 if (mSurface == 0 && mPreviewWindow == 0) { 610 LOG1("mSurface is not set yet."); 611 // still able to start preview in this case. 612 } 613 return startPreviewMode(); 614 case CAMERA_RECORDING_MODE: 615 if (mSurface == 0 && mPreviewWindow == 0) { 616 LOGE("mSurface or mPreviewWindow must be set before startRecordingMode."); 617 return INVALID_OPERATION; 618 } 619 return startRecordingMode(); 620 default: 621 return UNKNOWN_ERROR; 622 } 623} 624 625status_t CameraService::Client::startPreviewMode() { 626 LOG1("startPreviewMode"); 627 status_t result = NO_ERROR; 628 629 // if preview has been enabled, nothing needs to be done 630 if (mHardware->previewEnabled()) { 631 return NO_ERROR; 632 } 633 634 if (mUseOverlay) { 635 // If preview display has been set, set overlay now. 636 if (mSurface != 0) { 637 result = setOverlay(); 638 } 639 if (result != NO_ERROR) return result; 640 result = mHardware->startPreview(); 641 } else { 642 // XXX: Set the orientation of the ANativeWindow. 643 mHardware->setPreviewWindow(mPreviewWindow); 644 enableMsgType(CAMERA_MSG_PREVIEW_FRAME); 645 result = mHardware->startPreview(); 646 } 647 return result; 648} 649 650status_t CameraService::Client::startRecordingMode() { 651 LOG1("startRecordingMode"); 652 status_t result = NO_ERROR; 653 654 // if recording has been enabled, nothing needs to be done 655 if (mHardware->recordingEnabled()) { 656 return NO_ERROR; 657 } 658 659 // if preview has not been started, start preview first 660 if (!mHardware->previewEnabled()) { 661 result = startPreviewMode(); 662 if (result != NO_ERROR) { 663 return result; 664 } 665 } 666 667 // start recording mode 668 enableMsgType(CAMERA_MSG_VIDEO_FRAME); 669 mCameraService->playSound(SOUND_RECORDING); 670 result = mHardware->startRecording(); 671 if (result != NO_ERROR) { 672 LOGE("mHardware->startRecording() failed with status %d", result); 673 } 674 return result; 675} 676 677// stop preview mode 678void CameraService::Client::stopPreview() { 679 LOG1("stopPreview (pid %d)", getCallingPid()); 680 Mutex::Autolock lock(mLock); 681 if (checkPidAndHardware() != NO_ERROR) return; 682 683 684 disableMsgType(CAMERA_MSG_PREVIEW_FRAME); 685 mHardware->stopPreview(); 686 687 mPreviewBuffer.clear(); 688} 689 690// stop recording mode 691void CameraService::Client::stopRecording() { 692 LOG1("stopRecording (pid %d)", getCallingPid()); 693 Mutex::Autolock lock(mLock); 694 if (checkPidAndHardware() != NO_ERROR) return; 695 696 mCameraService->playSound(SOUND_RECORDING); 697 disableMsgType(CAMERA_MSG_VIDEO_FRAME); 698 mHardware->stopRecording(); 699 700 mPreviewBuffer.clear(); 701} 702 703// release a recording frame 704void CameraService::Client::releaseRecordingFrame(const sp<IMemory>& mem) { 705 Mutex::Autolock lock(mLock); 706 if (checkPidAndHardware() != NO_ERROR) return; 707 mHardware->releaseRecordingFrame(mem); 708} 709 710bool CameraService::Client::previewEnabled() { 711 LOG1("previewEnabled (pid %d)", getCallingPid()); 712 713 Mutex::Autolock lock(mLock); 714 if (checkPidAndHardware() != NO_ERROR) return false; 715 return mHardware->previewEnabled(); 716} 717 718bool CameraService::Client::recordingEnabled() { 719 LOG1("recordingEnabled (pid %d)", getCallingPid()); 720 721 Mutex::Autolock lock(mLock); 722 if (checkPidAndHardware() != NO_ERROR) return false; 723 return mHardware->recordingEnabled(); 724} 725 726status_t CameraService::Client::autoFocus() { 727 LOG1("autoFocus (pid %d)", getCallingPid()); 728 729 Mutex::Autolock lock(mLock); 730 status_t result = checkPidAndHardware(); 731 if (result != NO_ERROR) return result; 732 733 return mHardware->autoFocus(); 734} 735 736status_t CameraService::Client::cancelAutoFocus() { 737 LOG1("cancelAutoFocus (pid %d)", getCallingPid()); 738 739 Mutex::Autolock lock(mLock); 740 status_t result = checkPidAndHardware(); 741 if (result != NO_ERROR) return result; 742 743 return mHardware->cancelAutoFocus(); 744} 745 746// take a picture - image is returned in callback 747status_t CameraService::Client::takePicture() { 748 LOG1("takePicture (pid %d)", getCallingPid()); 749 750 Mutex::Autolock lock(mLock); 751 status_t result = checkPidAndHardware(); 752 if (result != NO_ERROR) return result; 753 754 enableMsgType(CAMERA_MSG_SHUTTER | 755 CAMERA_MSG_POSTVIEW_FRAME | 756 CAMERA_MSG_RAW_IMAGE | 757 CAMERA_MSG_COMPRESSED_IMAGE); 758 759 return mHardware->takePicture(); 760} 761 762// set preview/capture parameters - key/value pairs 763status_t CameraService::Client::setParameters(const String8& params) { 764 LOG1("setParameters (pid %d) (%s)", getCallingPid(), params.string()); 765 766 Mutex::Autolock lock(mLock); 767 status_t result = checkPidAndHardware(); 768 if (result != NO_ERROR) return result; 769 770 CameraParameters p(params); 771 return mHardware->setParameters(p); 772} 773 774// get preview/capture parameters - key/value pairs 775String8 CameraService::Client::getParameters() const { 776 Mutex::Autolock lock(mLock); 777 if (checkPidAndHardware() != NO_ERROR) return String8(); 778 779 String8 params(mHardware->getParameters().flatten()); 780 LOG1("getParameters (pid %d) (%s)", getCallingPid(), params.string()); 781 return params; 782} 783 784status_t CameraService::Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) { 785 LOG1("sendCommand (pid %d)", getCallingPid()); 786 Mutex::Autolock lock(mLock); 787 status_t result = checkPidAndHardware(); 788 if (result != NO_ERROR) return result; 789 790 if (cmd == CAMERA_CMD_SET_DISPLAY_ORIENTATION) { 791 // The orientation cannot be set during preview. 792 if (mHardware->previewEnabled()) { 793 return INVALID_OPERATION; 794 } 795 switch (arg1) { 796 case 0: 797 mOrientation = ISurface::BufferHeap::ROT_0; 798 break; 799 case 90: 800 mOrientation = ISurface::BufferHeap::ROT_90; 801 break; 802 case 180: 803 mOrientation = ISurface::BufferHeap::ROT_180; 804 break; 805 case 270: 806 mOrientation = ISurface::BufferHeap::ROT_270; 807 break; 808 default: 809 return BAD_VALUE; 810 } 811 return OK; 812 } 813 814 return mHardware->sendCommand(cmd, arg1, arg2); 815} 816 817// ---------------------------------------------------------------------------- 818 819void CameraService::Client::enableMsgType(int32_t msgType) { 820 android_atomic_or(msgType, &mMsgEnabled); 821 mHardware->enableMsgType(msgType); 822} 823 824void CameraService::Client::disableMsgType(int32_t msgType) { 825 android_atomic_and(~msgType, &mMsgEnabled); 826 mHardware->disableMsgType(msgType); 827} 828 829#define CHECK_MESSAGE_INTERVAL 10 // 10ms 830bool CameraService::Client::lockIfMessageWanted(int32_t msgType) { 831 int sleepCount = 0; 832 while (mMsgEnabled & msgType) { 833 if (mLock.tryLock() == NO_ERROR) { 834 if (sleepCount > 0) { 835 LOG1("lockIfMessageWanted(%d): waited for %d ms", 836 msgType, sleepCount * CHECK_MESSAGE_INTERVAL); 837 } 838 return true; 839 } 840 if (sleepCount++ == 0) { 841 LOG1("lockIfMessageWanted(%d): enter sleep", msgType); 842 } 843 usleep(CHECK_MESSAGE_INTERVAL * 1000); 844 } 845 LOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType); 846 return false; 847} 848 849// ---------------------------------------------------------------------------- 850 851// Converts from a raw pointer to the client to a strong pointer during a 852// hardware callback. This requires the callbacks only happen when the client 853// is still alive. 854sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) { 855 sp<Client> client = gCameraService->getClientById((int) user); 856 857 // This could happen if the Client is in the process of shutting down (the 858 // last strong reference is gone, but the destructor hasn't finished 859 // stopping the hardware). 860 if (client == 0) return NULL; 861 862 // The checks below are not necessary and are for debugging only. 863 if (client->mCameraService.get() != gCameraService) { 864 LOGE("mismatch service!"); 865 return NULL; 866 } 867 868 if (client->mHardware == 0) { 869 LOGE("mHardware == 0: callback after disconnect()?"); 870 return NULL; 871 } 872 873 return client; 874} 875 876// Callback messages can be dispatched to internal handlers or pass to our 877// client's callback functions, depending on the message type. 878// 879// notifyCallback: 880// CAMERA_MSG_SHUTTER handleShutter 881// (others) c->notifyCallback 882// dataCallback: 883// CAMERA_MSG_PREVIEW_FRAME handlePreviewData 884// CAMERA_MSG_POSTVIEW_FRAME handlePostview 885// CAMERA_MSG_RAW_IMAGE handleRawPicture 886// CAMERA_MSG_COMPRESSED_IMAGE handleCompressedPicture 887// (others) c->dataCallback 888// dataCallbackTimestamp 889// (others) c->dataCallbackTimestamp 890// 891// NOTE: the *Callback functions grab mLock of the client before passing 892// control to handle* functions. So the handle* functions must release the 893// lock before calling the ICameraClient's callbacks, so those callbacks can 894// invoke methods in the Client class again (For example, the preview frame 895// callback may want to releaseRecordingFrame). The handle* functions must 896// release the lock after all accesses to member variables, so it must be 897// handled very carefully. 898 899void CameraService::Client::notifyCallback(int32_t msgType, int32_t ext1, 900 int32_t ext2, void* user) { 901 LOG2("notifyCallback(%d)", msgType); 902 903 sp<Client> client = getClientFromCookie(user); 904 if (client == 0) return; 905 if (!client->lockIfMessageWanted(msgType)) return; 906 907 switch (msgType) { 908 case CAMERA_MSG_SHUTTER: 909 // ext1 is the dimension of the yuv picture. 910 client->handleShutter((image_rect_type *)ext1); 911 break; 912 default: 913 client->handleGenericNotify(msgType, ext1, ext2); 914 break; 915 } 916} 917 918void CameraService::Client::dataCallback(int32_t msgType, 919 const sp<IMemory>& dataPtr, void* user) { 920 LOG2("dataCallback(%d)", msgType); 921 922 sp<Client> client = getClientFromCookie(user); 923 if (client == 0) return; 924 if (!client->lockIfMessageWanted(msgType)) return; 925 926 if (dataPtr == 0) { 927 LOGE("Null data returned in data callback"); 928 client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0); 929 return; 930 } 931 932 switch (msgType) { 933 case CAMERA_MSG_PREVIEW_FRAME: 934 client->handlePreviewData(dataPtr); 935 break; 936 case CAMERA_MSG_POSTVIEW_FRAME: 937 client->handlePostview(dataPtr); 938 break; 939 case CAMERA_MSG_RAW_IMAGE: 940 client->handleRawPicture(dataPtr); 941 break; 942 case CAMERA_MSG_COMPRESSED_IMAGE: 943 client->handleCompressedPicture(dataPtr); 944 break; 945 default: 946 client->handleGenericData(msgType, dataPtr); 947 break; 948 } 949} 950 951void CameraService::Client::dataCallbackTimestamp(nsecs_t timestamp, 952 int32_t msgType, const sp<IMemory>& dataPtr, void* user) { 953 LOG2("dataCallbackTimestamp(%d)", msgType); 954 955 sp<Client> client = getClientFromCookie(user); 956 if (client == 0) return; 957 if (!client->lockIfMessageWanted(msgType)) return; 958 959 if (dataPtr == 0) { 960 LOGE("Null data returned in data with timestamp callback"); 961 client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0); 962 return; 963 } 964 965 client->handleGenericDataTimestamp(timestamp, msgType, dataPtr); 966} 967 968// snapshot taken callback 969// "size" is the width and height of yuv picture for registerBuffer. 970// If it is NULL, use the picture size from parameters. 971void CameraService::Client::handleShutter(image_rect_type *size) { 972 mCameraService->playSound(SOUND_SHUTTER); 973 974 sp<ICameraClient> c = mCameraClient; 975 if (c != 0) { 976 mLock.unlock(); 977 c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0); 978 if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return; 979 } 980 disableMsgType(CAMERA_MSG_SHUTTER); 981 982 // It takes some time before yuvPicture callback to be called. 983 // Register the buffer for raw image here to reduce latency. 984 if (mSurface != 0 && !mUseOverlay) { 985 int w, h; 986 CameraParameters params(mHardware->getParameters()); 987 if (size == NULL) { 988 params.getPictureSize(&w, &h); 989 } else { 990 w = size->width; 991 h = size->height; 992 w &= ~1; 993 h &= ~1; 994 LOG1("Snapshot image width=%d, height=%d", w, h); 995 } 996 // FIXME: don't use hardcoded format constants here 997 ISurface::BufferHeap buffers(w, h, w, h, 998 HAL_PIXEL_FORMAT_YCrCb_420_SP, mOrientation, 0, 999 mHardware->getRawHeap()); 1000 1001 IPCThreadState::self()->flushCommands(); 1002 } 1003 1004 mLock.unlock(); 1005} 1006 1007// preview callback - frame buffer update 1008void CameraService::Client::handlePreviewData(const sp<IMemory>& mem) { 1009 ssize_t offset; 1010 size_t size; 1011 sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); 1012 1013 // local copy of the callback flags 1014 int flags = mPreviewCallbackFlag; 1015 1016 // is callback enabled? 1017 if (!(flags & FRAME_CALLBACK_FLAG_ENABLE_MASK)) { 1018 // If the enable bit is off, the copy-out and one-shot bits are ignored 1019 LOG2("frame callback is disabled"); 1020 mLock.unlock(); 1021 return; 1022 } 1023 1024 // hold a strong pointer to the client 1025 sp<ICameraClient> c = mCameraClient; 1026 1027 // clear callback flags if no client or one-shot mode 1028 if (c == 0 || (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) { 1029 LOG2("Disable preview callback"); 1030 mPreviewCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK | 1031 FRAME_CALLBACK_FLAG_COPY_OUT_MASK | 1032 FRAME_CALLBACK_FLAG_ENABLE_MASK); 1033 if (mUseOverlay) { 1034 disableMsgType(CAMERA_MSG_PREVIEW_FRAME); 1035 } 1036 } 1037 1038 if (c != 0) { 1039 // Is the received frame copied out or not? 1040 if (flags & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) { 1041 LOG2("frame is copied"); 1042 copyFrameAndPostCopiedFrame(c, heap, offset, size); 1043 } else { 1044 LOG2("frame is forwarded"); 1045 mLock.unlock(); 1046 c->dataCallback(CAMERA_MSG_PREVIEW_FRAME, mem); 1047 } 1048 } else { 1049 mLock.unlock(); 1050 } 1051} 1052 1053// picture callback - postview image ready 1054void CameraService::Client::handlePostview(const sp<IMemory>& mem) { 1055 disableMsgType(CAMERA_MSG_POSTVIEW_FRAME); 1056 1057 sp<ICameraClient> c = mCameraClient; 1058 mLock.unlock(); 1059 if (c != 0) { 1060 c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem); 1061 } 1062} 1063 1064// picture callback - raw image ready 1065void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) { 1066 disableMsgType(CAMERA_MSG_RAW_IMAGE); 1067 1068 ssize_t offset; 1069 size_t size; 1070 sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); 1071 1072 sp<ICameraClient> c = mCameraClient; 1073 mLock.unlock(); 1074 if (c != 0) { 1075 c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem); 1076 } 1077} 1078 1079// picture callback - compressed picture ready 1080void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) { 1081 disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE); 1082 1083 sp<ICameraClient> c = mCameraClient; 1084 mLock.unlock(); 1085 if (c != 0) { 1086 c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem); 1087 } 1088} 1089 1090 1091void CameraService::Client::handleGenericNotify(int32_t msgType, 1092 int32_t ext1, int32_t ext2) { 1093 sp<ICameraClient> c = mCameraClient; 1094 mLock.unlock(); 1095 if (c != 0) { 1096 c->notifyCallback(msgType, ext1, ext2); 1097 } 1098} 1099 1100void CameraService::Client::handleGenericData(int32_t msgType, 1101 const sp<IMemory>& dataPtr) { 1102 sp<ICameraClient> c = mCameraClient; 1103 mLock.unlock(); 1104 if (c != 0) { 1105 c->dataCallback(msgType, dataPtr); 1106 } 1107} 1108 1109void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp, 1110 int32_t msgType, const sp<IMemory>& dataPtr) { 1111 sp<ICameraClient> c = mCameraClient; 1112 mLock.unlock(); 1113 if (c != 0) { 1114 c->dataCallbackTimestamp(timestamp, msgType, dataPtr); 1115 } 1116} 1117 1118void CameraService::Client::copyFrameAndPostCopiedFrame( 1119 const sp<ICameraClient>& client, const sp<IMemoryHeap>& heap, 1120 size_t offset, size_t size) { 1121 LOG2("copyFrameAndPostCopiedFrame"); 1122 // It is necessary to copy out of pmem before sending this to 1123 // the callback. For efficiency, reuse the same MemoryHeapBase 1124 // provided it's big enough. Don't allocate the memory or 1125 // perform the copy if there's no callback. 1126 // hold the preview lock while we grab a reference to the preview buffer 1127 sp<MemoryHeapBase> previewBuffer; 1128 1129 if (mPreviewBuffer == 0) { 1130 mPreviewBuffer = new MemoryHeapBase(size, 0, NULL); 1131 } else if (size > mPreviewBuffer->virtualSize()) { 1132 mPreviewBuffer.clear(); 1133 mPreviewBuffer = new MemoryHeapBase(size, 0, NULL); 1134 } 1135 if (mPreviewBuffer == 0) { 1136 LOGE("failed to allocate space for preview buffer"); 1137 mLock.unlock(); 1138 return; 1139 } 1140 previewBuffer = mPreviewBuffer; 1141 1142 memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size); 1143 1144 sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size); 1145 if (frame == 0) { 1146 LOGE("failed to allocate space for frame callback"); 1147 mLock.unlock(); 1148 return; 1149 } 1150 1151 mLock.unlock(); 1152 client->dataCallback(CAMERA_MSG_PREVIEW_FRAME, frame); 1153} 1154 1155// ---------------------------------------------------------------------------- 1156 1157static const int kDumpLockRetries = 50; 1158static const int kDumpLockSleep = 60000; 1159 1160static bool tryLock(Mutex& mutex) 1161{ 1162 bool locked = false; 1163 for (int i = 0; i < kDumpLockRetries; ++i) { 1164 if (mutex.tryLock() == NO_ERROR) { 1165 locked = true; 1166 break; 1167 } 1168 usleep(kDumpLockSleep); 1169 } 1170 return locked; 1171} 1172 1173status_t CameraService::dump(int fd, const Vector<String16>& args) { 1174 static const char* kDeadlockedString = "CameraService may be deadlocked\n"; 1175 1176 const size_t SIZE = 256; 1177 char buffer[SIZE]; 1178 String8 result; 1179 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 1180 snprintf(buffer, SIZE, "Permission Denial: " 1181 "can't dump CameraService from pid=%d, uid=%d\n", 1182 getCallingPid(), 1183 getCallingUid()); 1184 result.append(buffer); 1185 write(fd, result.string(), result.size()); 1186 } else { 1187 bool locked = tryLock(mServiceLock); 1188 // failed to lock - CameraService is probably deadlocked 1189 if (!locked) { 1190 String8 result(kDeadlockedString); 1191 write(fd, result.string(), result.size()); 1192 } 1193 1194 bool hasClient = false; 1195 for (int i = 0; i < mNumberOfCameras; i++) { 1196 sp<Client> client = mClient[i].promote(); 1197 if (client == 0) continue; 1198 hasClient = true; 1199 sprintf(buffer, "Client[%d] (%p) PID: %d\n", 1200 i, 1201 client->getCameraClient()->asBinder().get(), 1202 client->mClientPid); 1203 result.append(buffer); 1204 write(fd, result.string(), result.size()); 1205 client->mHardware->dump(fd, args); 1206 } 1207 if (!hasClient) { 1208 result.append("No camera client yet.\n"); 1209 write(fd, result.string(), result.size()); 1210 } 1211 1212 if (locked) mServiceLock.unlock(); 1213 1214 // change logging level 1215 int n = args.size(); 1216 for (int i = 0; i + 1 < n; i++) { 1217 if (args[i] == String16("-v")) { 1218 String8 levelStr(args[i+1]); 1219 int level = atoi(levelStr.string()); 1220 sprintf(buffer, "Set Log Level to %d", level); 1221 result.append(buffer); 1222 setLogLevel(level); 1223 } 1224 } 1225 } 1226 return NO_ERROR; 1227} 1228 1229sp<ISurface> CameraService::getISurface(const sp<Surface>& surface) { 1230 if (surface != 0) { 1231 return surface->getISurface(); 1232 } else { 1233 return sp<ISurface>(0); 1234 } 1235} 1236 1237}; // namespace android 1238