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