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