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