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