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