CameraService.cpp revision 7574da5a501fc9289fee49fdaf1fdb9d47dae2b6
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 461static void disconnectWindow(const sp<ANativeWindow>& window) { 462 if (window != 0) { 463 status_t result = native_window_disconnect(window.get(), 464 NATIVE_WINDOW_API_CAMERA); 465 if (result != NO_ERROR) { 466 LOGW("native_window_disconnect failed: %s (%d)", strerror(-result), 467 result); 468 } 469 } 470} 471 472void CameraService::Client::disconnect() { 473 int callingPid = getCallingPid(); 474 LOG1("disconnect E (pid %d)", callingPid); 475 Mutex::Autolock lock(mLock); 476 477 if (checkPid() != NO_ERROR) { 478 LOGW("different client - don't disconnect"); 479 return; 480 } 481 482 if (mClientPid <= 0) { 483 LOG1("camera is unlocked (mClientPid = %d), don't tear down hardware", mClientPid); 484 return; 485 } 486 487 // Make sure disconnect() is done once and once only, whether it is called 488 // from the user directly, or called by the destructor. 489 if (mHardware == 0) return; 490 491 LOG1("hardware teardown"); 492 // Before destroying mHardware, we must make sure it's in the 493 // idle state. 494 // Turn off all messages. 495 disableMsgType(CAMERA_MSG_ALL_MSGS); 496 mHardware->stopPreview(); 497 mHardware->cancelPicture(); 498 // Release the hardware resources. 499 mHardware->release(); 500 501 // Release the held ANativeWindow resources. 502 if (mPreviewWindow != 0) { 503 disconnectWindow(mPreviewWindow); 504 mPreviewWindow = 0; 505 mHardware->setPreviewWindow(mPreviewWindow); 506 } 507 mHardware.clear(); 508 509 mCameraService->removeClient(mCameraClient); 510 mCameraService->setCameraFree(mCameraId); 511 512 LOG1("disconnect X (pid %d)", callingPid); 513} 514 515// ---------------------------------------------------------------------------- 516 517status_t CameraService::Client::setPreviewWindow(const sp<IBinder>& binder, 518 const sp<ANativeWindow>& window) { 519 Mutex::Autolock lock(mLock); 520 status_t result = checkPidAndHardware(); 521 if (result != NO_ERROR) return result; 522 523 // return if no change in surface. 524 if (binder == mSurface) { 525 return NO_ERROR; 526 } 527 528 if (window != 0) { 529 result = native_window_connect(window.get(), NATIVE_WINDOW_API_CAMERA); 530 if (result != NO_ERROR) { 531 LOGE("native_window_connect failed: %s (%d)", strerror(-result), 532 result); 533 return result; 534 } 535 } 536 537 // If preview has been already started, register preview buffers now. 538 if (mHardware->previewEnabled()) { 539 if (window != 0) { 540 native_window_set_buffers_transform(window.get(), mOrientation); 541 result = mHardware->setPreviewWindow(window); 542 } 543 } 544 545 if (result == NO_ERROR) { 546 // Everything has succeeded. Disconnect the old window and remember the 547 // new window. 548 disconnectWindow(mPreviewWindow); 549 mSurface = binder; 550 mPreviewWindow = window; 551 } else { 552 // Something went wrong after we connected to the new window, so 553 // disconnect here. 554 disconnectWindow(window); 555 } 556 557 return result; 558} 559 560// set the Surface that the preview will use 561status_t CameraService::Client::setPreviewDisplay(const sp<Surface>& surface) { 562 LOG1("setPreviewDisplay(%p) (pid %d)", surface.get(), getCallingPid()); 563 564 sp<IBinder> binder(surface != 0 ? surface->asBinder() : 0); 565 sp<ANativeWindow> window(surface); 566 return setPreviewWindow(binder, window); 567} 568 569// set the SurfaceTexture that the preview will use 570status_t CameraService::Client::setPreviewTexture( 571 const sp<ISurfaceTexture>& surfaceTexture) { 572 LOG1("setPreviewTexture(%p) (pid %d)", surfaceTexture.get(), 573 getCallingPid()); 574 575 sp<IBinder> binder; 576 sp<ANativeWindow> window; 577 if (surfaceTexture != 0) { 578 binder = surfaceTexture->asBinder(); 579 window = new SurfaceTextureClient(surfaceTexture); 580 } 581 return setPreviewWindow(binder, window); 582} 583 584// set the preview callback flag to affect how the received frames from 585// preview are handled. 586void CameraService::Client::setPreviewCallbackFlag(int callback_flag) { 587 LOG1("setPreviewCallbackFlag(%d) (pid %d)", callback_flag, getCallingPid()); 588 Mutex::Autolock lock(mLock); 589 if (checkPidAndHardware() != NO_ERROR) return; 590 591 mPreviewCallbackFlag = callback_flag; 592 if (mPreviewCallbackFlag & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK) { 593 enableMsgType(CAMERA_MSG_PREVIEW_FRAME); 594 } else { 595 disableMsgType(CAMERA_MSG_PREVIEW_FRAME); 596 } 597} 598 599// start preview mode 600status_t CameraService::Client::startPreview() { 601 LOG1("startPreview (pid %d)", getCallingPid()); 602 return startCameraMode(CAMERA_PREVIEW_MODE); 603} 604 605// start recording mode 606status_t CameraService::Client::startRecording() { 607 LOG1("startRecording (pid %d)", getCallingPid()); 608 return startCameraMode(CAMERA_RECORDING_MODE); 609} 610 611// start preview or recording 612status_t CameraService::Client::startCameraMode(camera_mode mode) { 613 LOG1("startCameraMode(%d)", mode); 614 Mutex::Autolock lock(mLock); 615 status_t result = checkPidAndHardware(); 616 if (result != NO_ERROR) return result; 617 618 switch(mode) { 619 case CAMERA_PREVIEW_MODE: 620 if (mSurface == 0 && mPreviewWindow == 0) { 621 LOG1("mSurface is not set yet."); 622 // still able to start preview in this case. 623 } 624 return startPreviewMode(); 625 case CAMERA_RECORDING_MODE: 626 if (mSurface == 0 && mPreviewWindow == 0) { 627 LOGE("mSurface or mPreviewWindow must be set before startRecordingMode."); 628 return INVALID_OPERATION; 629 } 630 return startRecordingMode(); 631 default: 632 return UNKNOWN_ERROR; 633 } 634} 635 636status_t CameraService::Client::startPreviewMode() { 637 LOG1("startPreviewMode"); 638 status_t result = NO_ERROR; 639 640 // if preview has been enabled, nothing needs to be done 641 if (mHardware->previewEnabled()) { 642 return NO_ERROR; 643 } 644 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 715status_t CameraService::Client::storeMetaDataInBuffers(bool enabled) 716{ 717 LOG1("storeMetaDataInBuffers: %s", enabled? "true": "false"); 718 Mutex::Autolock lock(mLock); 719 if (checkPidAndHardware() != NO_ERROR) { 720 return UNKNOWN_ERROR; 721 } 722 return mHardware->storeMetaDataInBuffers(enabled); 723} 724 725bool CameraService::Client::previewEnabled() { 726 LOG1("previewEnabled (pid %d)", getCallingPid()); 727 728 Mutex::Autolock lock(mLock); 729 if (checkPidAndHardware() != NO_ERROR) return false; 730 return mHardware->previewEnabled(); 731} 732 733bool CameraService::Client::recordingEnabled() { 734 LOG1("recordingEnabled (pid %d)", getCallingPid()); 735 736 Mutex::Autolock lock(mLock); 737 if (checkPidAndHardware() != NO_ERROR) return false; 738 return mHardware->recordingEnabled(); 739} 740 741status_t CameraService::Client::autoFocus() { 742 LOG1("autoFocus (pid %d)", getCallingPid()); 743 744 Mutex::Autolock lock(mLock); 745 status_t result = checkPidAndHardware(); 746 if (result != NO_ERROR) return result; 747 748 return mHardware->autoFocus(); 749} 750 751status_t CameraService::Client::cancelAutoFocus() { 752 LOG1("cancelAutoFocus (pid %d)", getCallingPid()); 753 754 Mutex::Autolock lock(mLock); 755 status_t result = checkPidAndHardware(); 756 if (result != NO_ERROR) return result; 757 758 return mHardware->cancelAutoFocus(); 759} 760 761// take a picture - image is returned in callback 762status_t CameraService::Client::takePicture(int msgType) { 763 LOG1("takePicture (pid %d): 0x%x", getCallingPid(), msgType); 764 765 Mutex::Autolock lock(mLock); 766 status_t result = checkPidAndHardware(); 767 if (result != NO_ERROR) return result; 768 769 if (mHardware->recordingEnabled()) { 770 LOGE("Cannot take picture during recording."); 771 return INVALID_OPERATION; 772 } 773 774 if ((msgType & CAMERA_MSG_RAW_IMAGE) && 775 (msgType & CAMERA_MSG_RAW_IMAGE_NOTIFY)) { 776 LOGE("CAMERA_MSG_RAW_IMAGE and CAMERA_MSG_RAW_IMAGE_NOTIFY" 777 " cannot be both enabled"); 778 return BAD_VALUE; 779 } 780 781 // We only accept picture related message types 782 // and ignore other types of messages for takePicture(). 783 int picMsgType = msgType 784 & (CAMERA_MSG_SHUTTER | 785 CAMERA_MSG_POSTVIEW_FRAME | 786 CAMERA_MSG_RAW_IMAGE | 787 CAMERA_MSG_RAW_IMAGE_NOTIFY | 788 CAMERA_MSG_COMPRESSED_IMAGE); 789 790 enableMsgType(picMsgType); 791 792 return mHardware->takePicture(); 793} 794 795// set preview/capture parameters - key/value pairs 796status_t CameraService::Client::setParameters(const String8& params) { 797 LOG1("setParameters (pid %d) (%s)", getCallingPid(), params.string()); 798 799 Mutex::Autolock lock(mLock); 800 status_t result = checkPidAndHardware(); 801 if (result != NO_ERROR) return result; 802 803 CameraParameters p(params); 804 return mHardware->setParameters(p); 805} 806 807// get preview/capture parameters - key/value pairs 808String8 CameraService::Client::getParameters() const { 809 Mutex::Autolock lock(mLock); 810 if (checkPidAndHardware() != NO_ERROR) return String8(); 811 812 String8 params(mHardware->getParameters().flatten()); 813 LOG1("getParameters (pid %d) (%s)", getCallingPid(), params.string()); 814 return params; 815} 816 817// enable shutter sound 818status_t CameraService::Client::enableShutterSound(bool enable) { 819 LOG1("enableShutterSound (pid %d)", getCallingPid()); 820 821 status_t result = checkPidAndHardware(); 822 if (result != NO_ERROR) return result; 823 824 if (enable) { 825 mPlayShutterSound = true; 826 return OK; 827 } 828 829 // Disabling shutter sound may not be allowed. In that case only 830 // allow the mediaserver process to disable the sound. 831 char value[PROPERTY_VALUE_MAX]; 832 property_get("ro.camera.sound.forced", value, "0"); 833 if (strcmp(value, "0") != 0) { 834 // Disabling shutter sound is not allowed. Deny if the current 835 // process is not mediaserver. 836 if (getCallingPid() != getpid()) { 837 LOGE("Failed to disable shutter sound. Permission denied (pid %d)", getCallingPid()); 838 return PERMISSION_DENIED; 839 } 840 } 841 842 mPlayShutterSound = false; 843 return OK; 844} 845 846status_t CameraService::Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) { 847 LOG1("sendCommand (pid %d)", getCallingPid()); 848 int orientation; 849 Mutex::Autolock lock(mLock); 850 status_t result = checkPidAndHardware(); 851 if (result != NO_ERROR) return result; 852 853 if (cmd == CAMERA_CMD_SET_DISPLAY_ORIENTATION) { 854 // The orientation cannot be set during preview. 855 if (mHardware->previewEnabled()) { 856 return INVALID_OPERATION; 857 } 858 // Mirror the preview if the camera is front-facing. 859 orientation = getOrientation(arg1, mCameraFacing == CAMERA_FACING_FRONT); 860 if (orientation == -1) return BAD_VALUE; 861 862 if (mOrientation != orientation) { 863 mOrientation = orientation; 864 } 865 return OK; 866 } else if (cmd == CAMERA_CMD_ENABLE_SHUTTER_SOUND) { 867 switch (arg1) { 868 case 0: 869 enableShutterSound(false); 870 break; 871 case 1: 872 enableShutterSound(true); 873 break; 874 default: 875 return BAD_VALUE; 876 } 877 return OK; 878 } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) { 879 mCameraService->playSound(SOUND_RECORDING); 880 } 881 882 return mHardware->sendCommand(cmd, arg1, arg2); 883} 884 885// ---------------------------------------------------------------------------- 886 887void CameraService::Client::enableMsgType(int32_t msgType) { 888 android_atomic_or(msgType, &mMsgEnabled); 889 mHardware->enableMsgType(msgType); 890} 891 892void CameraService::Client::disableMsgType(int32_t msgType) { 893 android_atomic_and(~msgType, &mMsgEnabled); 894 mHardware->disableMsgType(msgType); 895} 896 897#define CHECK_MESSAGE_INTERVAL 10 // 10ms 898bool CameraService::Client::lockIfMessageWanted(int32_t msgType) { 899 int sleepCount = 0; 900 while (mMsgEnabled & msgType) { 901 if (mLock.tryLock() == NO_ERROR) { 902 if (sleepCount > 0) { 903 LOG1("lockIfMessageWanted(%d): waited for %d ms", 904 msgType, sleepCount * CHECK_MESSAGE_INTERVAL); 905 } 906 return true; 907 } 908 if (sleepCount++ == 0) { 909 LOG1("lockIfMessageWanted(%d): enter sleep", msgType); 910 } 911 usleep(CHECK_MESSAGE_INTERVAL * 1000); 912 } 913 LOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType); 914 return false; 915} 916 917// ---------------------------------------------------------------------------- 918 919// Converts from a raw pointer to the client to a strong pointer during a 920// hardware callback. This requires the callbacks only happen when the client 921// is still alive. 922sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) { 923 sp<Client> client = gCameraService->getClientById((int) user); 924 925 // This could happen if the Client is in the process of shutting down (the 926 // last strong reference is gone, but the destructor hasn't finished 927 // stopping the hardware). 928 if (client == 0) return NULL; 929 930 // The checks below are not necessary and are for debugging only. 931 if (client->mCameraService.get() != gCameraService) { 932 LOGE("mismatch service!"); 933 return NULL; 934 } 935 936 if (client->mHardware == 0) { 937 LOGE("mHardware == 0: callback after disconnect()?"); 938 return NULL; 939 } 940 941 return client; 942} 943 944// Callback messages can be dispatched to internal handlers or pass to our 945// client's callback functions, depending on the message type. 946// 947// notifyCallback: 948// CAMERA_MSG_SHUTTER handleShutter 949// (others) c->notifyCallback 950// dataCallback: 951// CAMERA_MSG_PREVIEW_FRAME handlePreviewData 952// CAMERA_MSG_POSTVIEW_FRAME handlePostview 953// CAMERA_MSG_RAW_IMAGE handleRawPicture 954// CAMERA_MSG_COMPRESSED_IMAGE handleCompressedPicture 955// (others) c->dataCallback 956// dataCallbackTimestamp 957// (others) c->dataCallbackTimestamp 958// 959// NOTE: the *Callback functions grab mLock of the client before passing 960// control to handle* functions. So the handle* functions must release the 961// lock before calling the ICameraClient's callbacks, so those callbacks can 962// invoke methods in the Client class again (For example, the preview frame 963// callback may want to releaseRecordingFrame). The handle* functions must 964// release the lock after all accesses to member variables, so it must be 965// handled very carefully. 966 967void CameraService::Client::notifyCallback(int32_t msgType, int32_t ext1, 968 int32_t ext2, void* user) { 969 LOG2("notifyCallback(%d)", msgType); 970 971 sp<Client> client = getClientFromCookie(user); 972 if (client == 0) return; 973 if (!client->lockIfMessageWanted(msgType)) return; 974 975 switch (msgType) { 976 case CAMERA_MSG_SHUTTER: 977 // ext1 is the dimension of the yuv picture. 978 client->handleShutter(); 979 break; 980 default: 981 client->handleGenericNotify(msgType, ext1, ext2); 982 break; 983 } 984} 985 986void CameraService::Client::dataCallback(int32_t msgType, 987 const sp<IMemory>& dataPtr, void* user) { 988 LOG2("dataCallback(%d)", msgType); 989 990 sp<Client> client = getClientFromCookie(user); 991 if (client == 0) return; 992 if (!client->lockIfMessageWanted(msgType)) return; 993 994 if (dataPtr == 0) { 995 LOGE("Null data returned in data callback"); 996 client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0); 997 return; 998 } 999 1000 switch (msgType) { 1001 case CAMERA_MSG_PREVIEW_FRAME: 1002 client->handlePreviewData(dataPtr); 1003 break; 1004 case CAMERA_MSG_POSTVIEW_FRAME: 1005 client->handlePostview(dataPtr); 1006 break; 1007 case CAMERA_MSG_RAW_IMAGE: 1008 client->handleRawPicture(dataPtr); 1009 break; 1010 case CAMERA_MSG_COMPRESSED_IMAGE: 1011 client->handleCompressedPicture(dataPtr); 1012 break; 1013 default: 1014 client->handleGenericData(msgType, dataPtr); 1015 break; 1016 } 1017} 1018 1019void CameraService::Client::dataCallbackTimestamp(nsecs_t timestamp, 1020 int32_t msgType, const sp<IMemory>& dataPtr, void* user) { 1021 LOG2("dataCallbackTimestamp(%d)", msgType); 1022 1023 sp<Client> client = getClientFromCookie(user); 1024 if (client == 0) return; 1025 if (!client->lockIfMessageWanted(msgType)) return; 1026 1027 if (dataPtr == 0) { 1028 LOGE("Null data returned in data with timestamp callback"); 1029 client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0); 1030 return; 1031 } 1032 1033 client->handleGenericDataTimestamp(timestamp, msgType, dataPtr); 1034} 1035 1036// snapshot taken callback 1037void CameraService::Client::handleShutter(void) { 1038 if (mPlayShutterSound) { 1039 mCameraService->playSound(SOUND_SHUTTER); 1040 } 1041 1042 sp<ICameraClient> c = mCameraClient; 1043 if (c != 0) { 1044 mLock.unlock(); 1045 c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0); 1046 if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return; 1047 } 1048 disableMsgType(CAMERA_MSG_SHUTTER); 1049 1050 mLock.unlock(); 1051} 1052 1053// preview callback - frame buffer update 1054void CameraService::Client::handlePreviewData(const sp<IMemory>& mem) { 1055 ssize_t offset; 1056 size_t size; 1057 sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); 1058 1059 // local copy of the callback flags 1060 int flags = mPreviewCallbackFlag; 1061 1062 // is callback enabled? 1063 if (!(flags & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK)) { 1064 // If the enable bit is off, the copy-out and one-shot bits are ignored 1065 LOG2("frame callback is disabled"); 1066 mLock.unlock(); 1067 return; 1068 } 1069 1070 // hold a strong pointer to the client 1071 sp<ICameraClient> c = mCameraClient; 1072 1073 // clear callback flags if no client or one-shot mode 1074 if (c == 0 || (mPreviewCallbackFlag & CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) { 1075 LOG2("Disable preview callback"); 1076 mPreviewCallbackFlag &= ~(CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK | 1077 CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK | 1078 CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK); 1079 disableMsgType(CAMERA_MSG_PREVIEW_FRAME); 1080 } 1081 1082 if (c != 0) { 1083 // Is the received frame copied out or not? 1084 if (flags & CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK) { 1085 LOG2("frame is copied"); 1086 copyFrameAndPostCopiedFrame(c, heap, offset, size); 1087 } else { 1088 LOG2("frame is forwarded"); 1089 mLock.unlock(); 1090 c->dataCallback(CAMERA_MSG_PREVIEW_FRAME, mem); 1091 } 1092 } else { 1093 mLock.unlock(); 1094 } 1095} 1096 1097// picture callback - postview image ready 1098void CameraService::Client::handlePostview(const sp<IMemory>& mem) { 1099 disableMsgType(CAMERA_MSG_POSTVIEW_FRAME); 1100 1101 sp<ICameraClient> c = mCameraClient; 1102 mLock.unlock(); 1103 if (c != 0) { 1104 c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem); 1105 } 1106} 1107 1108// picture callback - raw image ready 1109void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) { 1110 disableMsgType(CAMERA_MSG_RAW_IMAGE); 1111 1112 ssize_t offset; 1113 size_t size; 1114 sp<IMemoryHeap> heap = mem->getMemory(&offset, &size); 1115 1116 sp<ICameraClient> c = mCameraClient; 1117 mLock.unlock(); 1118 if (c != 0) { 1119 c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem); 1120 } 1121} 1122 1123// picture callback - compressed picture ready 1124void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) { 1125 disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE); 1126 1127 sp<ICameraClient> c = mCameraClient; 1128 mLock.unlock(); 1129 if (c != 0) { 1130 c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem); 1131 } 1132} 1133 1134 1135void CameraService::Client::handleGenericNotify(int32_t msgType, 1136 int32_t ext1, int32_t ext2) { 1137 sp<ICameraClient> c = mCameraClient; 1138 mLock.unlock(); 1139 if (c != 0) { 1140 c->notifyCallback(msgType, ext1, ext2); 1141 } 1142} 1143 1144void CameraService::Client::handleGenericData(int32_t msgType, 1145 const sp<IMemory>& dataPtr) { 1146 sp<ICameraClient> c = mCameraClient; 1147 mLock.unlock(); 1148 if (c != 0) { 1149 c->dataCallback(msgType, dataPtr); 1150 } 1151} 1152 1153void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp, 1154 int32_t msgType, const sp<IMemory>& dataPtr) { 1155 sp<ICameraClient> c = mCameraClient; 1156 mLock.unlock(); 1157 if (c != 0) { 1158 c->dataCallbackTimestamp(timestamp, msgType, dataPtr); 1159 } 1160} 1161 1162void CameraService::Client::copyFrameAndPostCopiedFrame( 1163 const sp<ICameraClient>& client, const sp<IMemoryHeap>& heap, 1164 size_t offset, size_t size) { 1165 LOG2("copyFrameAndPostCopiedFrame"); 1166 // It is necessary to copy out of pmem before sending this to 1167 // the callback. For efficiency, reuse the same MemoryHeapBase 1168 // provided it's big enough. Don't allocate the memory or 1169 // perform the copy if there's no callback. 1170 // hold the preview lock while we grab a reference to the preview buffer 1171 sp<MemoryHeapBase> previewBuffer; 1172 1173 if (mPreviewBuffer == 0) { 1174 mPreviewBuffer = new MemoryHeapBase(size, 0, NULL); 1175 } else if (size > mPreviewBuffer->virtualSize()) { 1176 mPreviewBuffer.clear(); 1177 mPreviewBuffer = new MemoryHeapBase(size, 0, NULL); 1178 } 1179 if (mPreviewBuffer == 0) { 1180 LOGE("failed to allocate space for preview buffer"); 1181 mLock.unlock(); 1182 return; 1183 } 1184 previewBuffer = mPreviewBuffer; 1185 1186 memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size); 1187 1188 sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size); 1189 if (frame == 0) { 1190 LOGE("failed to allocate space for frame callback"); 1191 mLock.unlock(); 1192 return; 1193 } 1194 1195 mLock.unlock(); 1196 client->dataCallback(CAMERA_MSG_PREVIEW_FRAME, frame); 1197} 1198 1199int CameraService::Client::getOrientation(int degrees, bool mirror) { 1200 if (!mirror) { 1201 if (degrees == 0) return 0; 1202 else if (degrees == 90) return HAL_TRANSFORM_ROT_90; 1203 else if (degrees == 180) return HAL_TRANSFORM_ROT_180; 1204 else if (degrees == 270) return HAL_TRANSFORM_ROT_270; 1205 } else { // Do mirror (horizontal flip) 1206 if (degrees == 0) { // FLIP_H and ROT_0 1207 return HAL_TRANSFORM_FLIP_H; 1208 } else if (degrees == 90) { // FLIP_H and ROT_90 1209 return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90; 1210 } else if (degrees == 180) { // FLIP_H and ROT_180 1211 return HAL_TRANSFORM_FLIP_V; 1212 } else if (degrees == 270) { // FLIP_H and ROT_270 1213 return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90; 1214 } 1215 } 1216 LOGE("Invalid setDisplayOrientation degrees=%d", degrees); 1217 return -1; 1218} 1219 1220 1221// ---------------------------------------------------------------------------- 1222 1223static const int kDumpLockRetries = 50; 1224static const int kDumpLockSleep = 60000; 1225 1226static bool tryLock(Mutex& mutex) 1227{ 1228 bool locked = false; 1229 for (int i = 0; i < kDumpLockRetries; ++i) { 1230 if (mutex.tryLock() == NO_ERROR) { 1231 locked = true; 1232 break; 1233 } 1234 usleep(kDumpLockSleep); 1235 } 1236 return locked; 1237} 1238 1239status_t CameraService::dump(int fd, const Vector<String16>& args) { 1240 static const char* kDeadlockedString = "CameraService may be deadlocked\n"; 1241 1242 const size_t SIZE = 256; 1243 char buffer[SIZE]; 1244 String8 result; 1245 if (checkCallingPermission(String16("android.permission.DUMP")) == false) { 1246 snprintf(buffer, SIZE, "Permission Denial: " 1247 "can't dump CameraService from pid=%d, uid=%d\n", 1248 getCallingPid(), 1249 getCallingUid()); 1250 result.append(buffer); 1251 write(fd, result.string(), result.size()); 1252 } else { 1253 bool locked = tryLock(mServiceLock); 1254 // failed to lock - CameraService is probably deadlocked 1255 if (!locked) { 1256 String8 result(kDeadlockedString); 1257 write(fd, result.string(), result.size()); 1258 } 1259 1260 bool hasClient = false; 1261 for (int i = 0; i < mNumberOfCameras; i++) { 1262 sp<Client> client = mClient[i].promote(); 1263 if (client == 0) continue; 1264 hasClient = true; 1265 sprintf(buffer, "Client[%d] (%p) PID: %d\n", 1266 i, 1267 client->getCameraClient()->asBinder().get(), 1268 client->mClientPid); 1269 result.append(buffer); 1270 write(fd, result.string(), result.size()); 1271 client->mHardware->dump(fd, args); 1272 } 1273 if (!hasClient) { 1274 result.append("No camera client yet.\n"); 1275 write(fd, result.string(), result.size()); 1276 } 1277 1278 if (locked) mServiceLock.unlock(); 1279 1280 // change logging level 1281 int n = args.size(); 1282 for (int i = 0; i + 1 < n; i++) { 1283 if (args[i] == String16("-v")) { 1284 String8 levelStr(args[i+1]); 1285 int level = atoi(levelStr.string()); 1286 sprintf(buffer, "Set Log Level to %d", level); 1287 result.append(buffer); 1288 setLogLevel(level); 1289 } 1290 } 1291 } 1292 return NO_ERROR; 1293} 1294 1295}; // namespace android 1296