blob: 355763e6512c9fa40618fddba8f77f686017a79a [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;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700843 }
844
845 return mHardware->sendCommand(cmd, arg1, arg2);
846}
847
848// ----------------------------------------------------------------------------
849
850void CameraService::Client::enableMsgType(int32_t msgType) {
851 android_atomic_or(msgType, &mMsgEnabled);
852 mHardware->enableMsgType(msgType);
853}
854
855void CameraService::Client::disableMsgType(int32_t msgType) {
856 android_atomic_and(~msgType, &mMsgEnabled);
857 mHardware->disableMsgType(msgType);
858}
859
860#define CHECK_MESSAGE_INTERVAL 10 // 10ms
861bool CameraService::Client::lockIfMessageWanted(int32_t msgType) {
862 int sleepCount = 0;
863 while (mMsgEnabled & msgType) {
864 if (mLock.tryLock() == NO_ERROR) {
865 if (sleepCount > 0) {
866 LOG1("lockIfMessageWanted(%d): waited for %d ms",
867 msgType, sleepCount * CHECK_MESSAGE_INTERVAL);
868 }
869 return true;
870 }
871 if (sleepCount++ == 0) {
872 LOG1("lockIfMessageWanted(%d): enter sleep", msgType);
873 }
874 usleep(CHECK_MESSAGE_INTERVAL * 1000);
875 }
876 LOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType);
877 return false;
878}
879
880// ----------------------------------------------------------------------------
881
882// Converts from a raw pointer to the client to a strong pointer during a
883// hardware callback. This requires the callbacks only happen when the client
884// is still alive.
885sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
886 sp<Client> client = gCameraService->getClientById((int) user);
887
888 // This could happen if the Client is in the process of shutting down (the
889 // last strong reference is gone, but the destructor hasn't finished
890 // stopping the hardware).
891 if (client == 0) return NULL;
892
893 // The checks below are not necessary and are for debugging only.
894 if (client->mCameraService.get() != gCameraService) {
895 LOGE("mismatch service!");
896 return NULL;
897 }
898
899 if (client->mHardware == 0) {
900 LOGE("mHardware == 0: callback after disconnect()?");
901 return NULL;
902 }
903
904 return client;
905}
906
907// Callback messages can be dispatched to internal handlers or pass to our
908// client's callback functions, depending on the message type.
909//
910// notifyCallback:
911// CAMERA_MSG_SHUTTER handleShutter
912// (others) c->notifyCallback
913// dataCallback:
914// CAMERA_MSG_PREVIEW_FRAME handlePreviewData
915// CAMERA_MSG_POSTVIEW_FRAME handlePostview
916// CAMERA_MSG_RAW_IMAGE handleRawPicture
917// CAMERA_MSG_COMPRESSED_IMAGE handleCompressedPicture
918// (others) c->dataCallback
919// dataCallbackTimestamp
920// (others) c->dataCallbackTimestamp
921//
922// NOTE: the *Callback functions grab mLock of the client before passing
923// control to handle* functions. So the handle* functions must release the
924// lock before calling the ICameraClient's callbacks, so those callbacks can
925// invoke methods in the Client class again (For example, the preview frame
926// callback may want to releaseRecordingFrame). The handle* functions must
927// release the lock after all accesses to member variables, so it must be
928// handled very carefully.
929
930void CameraService::Client::notifyCallback(int32_t msgType, int32_t ext1,
931 int32_t ext2, void* user) {
932 LOG2("notifyCallback(%d)", msgType);
933
934 sp<Client> client = getClientFromCookie(user);
935 if (client == 0) return;
936 if (!client->lockIfMessageWanted(msgType)) return;
937
938 switch (msgType) {
939 case CAMERA_MSG_SHUTTER:
940 // ext1 is the dimension of the yuv picture.
941 client->handleShutter((image_rect_type *)ext1);
942 break;
943 default:
944 client->handleGenericNotify(msgType, ext1, ext2);
945 break;
946 }
947}
948
949void CameraService::Client::dataCallback(int32_t msgType,
950 const sp<IMemory>& dataPtr, void* user) {
951 LOG2("dataCallback(%d)", msgType);
952
953 sp<Client> client = getClientFromCookie(user);
954 if (client == 0) return;
955 if (!client->lockIfMessageWanted(msgType)) return;
956
957 if (dataPtr == 0) {
958 LOGE("Null data returned in data callback");
959 client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
960 return;
961 }
962
963 switch (msgType) {
964 case CAMERA_MSG_PREVIEW_FRAME:
965 client->handlePreviewData(dataPtr);
966 break;
967 case CAMERA_MSG_POSTVIEW_FRAME:
968 client->handlePostview(dataPtr);
969 break;
970 case CAMERA_MSG_RAW_IMAGE:
971 client->handleRawPicture(dataPtr);
972 break;
973 case CAMERA_MSG_COMPRESSED_IMAGE:
974 client->handleCompressedPicture(dataPtr);
975 break;
976 default:
977 client->handleGenericData(msgType, dataPtr);
978 break;
979 }
980}
981
982void CameraService::Client::dataCallbackTimestamp(nsecs_t timestamp,
983 int32_t msgType, const sp<IMemory>& dataPtr, void* user) {
984 LOG2("dataCallbackTimestamp(%d)", msgType);
985
986 sp<Client> client = getClientFromCookie(user);
987 if (client == 0) return;
988 if (!client->lockIfMessageWanted(msgType)) return;
989
990 if (dataPtr == 0) {
991 LOGE("Null data returned in data with timestamp callback");
992 client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
993 return;
994 }
995
996 client->handleGenericDataTimestamp(timestamp, msgType, dataPtr);
997}
998
999// snapshot taken callback
1000// "size" is the width and height of yuv picture for registerBuffer.
1001// If it is NULL, use the picture size from parameters.
1002void CameraService::Client::handleShutter(image_rect_type *size) {
Nipun Kwatrab5ca4612010-09-11 19:31:10 -07001003 if (mPlayShutterSound) {
1004 mCameraService->playSound(SOUND_SHUTTER);
1005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001006
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 sp<ICameraClient> c = mCameraClient;
1008 if (c != 0) {
1009 mLock.unlock();
1010 c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0);
1011 if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return;
1012 }
1013 disableMsgType(CAMERA_MSG_SHUTTER);
1014
1015 // It takes some time before yuvPicture callback to be called.
1016 // Register the buffer for raw image here to reduce latency.
1017 if (mSurface != 0 && !mUseOverlay) {
1018 int w, h;
1019 CameraParameters params(mHardware->getParameters());
1020 if (size == NULL) {
1021 params.getPictureSize(&w, &h);
1022 } else {
1023 w = size->width;
1024 h = size->height;
1025 w &= ~1;
1026 h &= ~1;
1027 LOG1("Snapshot image width=%d, height=%d", w, h);
1028 }
1029 // FIXME: don't use hardcoded format constants here
1030 ISurface::BufferHeap buffers(w, h, w, h,
1031 HAL_PIXEL_FORMAT_YCrCb_420_SP, mOrientation, 0,
1032 mHardware->getRawHeap());
1033
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034 IPCThreadState::self()->flushCommands();
1035 }
1036
1037 mLock.unlock();
1038}
1039
1040// preview callback - frame buffer update
1041void CameraService::Client::handlePreviewData(const sp<IMemory>& mem) {
1042 ssize_t offset;
1043 size_t size;
1044 sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1045
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046 // local copy of the callback flags
1047 int flags = mPreviewCallbackFlag;
1048
1049 // is callback enabled?
1050 if (!(flags & FRAME_CALLBACK_FLAG_ENABLE_MASK)) {
1051 // If the enable bit is off, the copy-out and one-shot bits are ignored
1052 LOG2("frame callback is disabled");
1053 mLock.unlock();
1054 return;
1055 }
1056
1057 // hold a strong pointer to the client
1058 sp<ICameraClient> c = mCameraClient;
1059
1060 // clear callback flags if no client or one-shot mode
1061 if (c == 0 || (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) {
1062 LOG2("Disable preview callback");
1063 mPreviewCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK |
1064 FRAME_CALLBACK_FLAG_COPY_OUT_MASK |
1065 FRAME_CALLBACK_FLAG_ENABLE_MASK);
Wu-cheng Li0667de72010-09-03 16:40:32 -07001066 disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001067 }
1068
1069 if (c != 0) {
1070 // Is the received frame copied out or not?
1071 if (flags & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) {
1072 LOG2("frame is copied");
1073 copyFrameAndPostCopiedFrame(c, heap, offset, size);
1074 } else {
1075 LOG2("frame is forwarded");
1076 mLock.unlock();
1077 c->dataCallback(CAMERA_MSG_PREVIEW_FRAME, mem);
1078 }
1079 } else {
1080 mLock.unlock();
1081 }
1082}
1083
1084// picture callback - postview image ready
1085void CameraService::Client::handlePostview(const sp<IMemory>& mem) {
1086 disableMsgType(CAMERA_MSG_POSTVIEW_FRAME);
1087
1088 sp<ICameraClient> c = mCameraClient;
1089 mLock.unlock();
1090 if (c != 0) {
1091 c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem);
1092 }
1093}
1094
1095// picture callback - raw image ready
1096void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) {
1097 disableMsgType(CAMERA_MSG_RAW_IMAGE);
1098
1099 ssize_t offset;
1100 size_t size;
1101 sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1102
Mathias Agopian65ab4712010-07-14 17:59:35 -07001103 sp<ICameraClient> c = mCameraClient;
1104 mLock.unlock();
1105 if (c != 0) {
1106 c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem);
1107 }
1108}
1109
1110// picture callback - compressed picture ready
1111void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) {
1112 disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
1113
1114 sp<ICameraClient> c = mCameraClient;
1115 mLock.unlock();
1116 if (c != 0) {
1117 c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem);
1118 }
1119}
1120
1121
1122void CameraService::Client::handleGenericNotify(int32_t msgType,
1123 int32_t ext1, int32_t ext2) {
1124 sp<ICameraClient> c = mCameraClient;
1125 mLock.unlock();
1126 if (c != 0) {
1127 c->notifyCallback(msgType, ext1, ext2);
1128 }
1129}
1130
1131void CameraService::Client::handleGenericData(int32_t msgType,
1132 const sp<IMemory>& dataPtr) {
1133 sp<ICameraClient> c = mCameraClient;
1134 mLock.unlock();
1135 if (c != 0) {
1136 c->dataCallback(msgType, dataPtr);
1137 }
1138}
1139
1140void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp,
1141 int32_t msgType, const sp<IMemory>& dataPtr) {
1142 sp<ICameraClient> c = mCameraClient;
1143 mLock.unlock();
1144 if (c != 0) {
1145 c->dataCallbackTimestamp(timestamp, msgType, dataPtr);
1146 }
1147}
1148
1149void CameraService::Client::copyFrameAndPostCopiedFrame(
1150 const sp<ICameraClient>& client, const sp<IMemoryHeap>& heap,
1151 size_t offset, size_t size) {
1152 LOG2("copyFrameAndPostCopiedFrame");
1153 // It is necessary to copy out of pmem before sending this to
1154 // the callback. For efficiency, reuse the same MemoryHeapBase
1155 // provided it's big enough. Don't allocate the memory or
1156 // perform the copy if there's no callback.
1157 // hold the preview lock while we grab a reference to the preview buffer
1158 sp<MemoryHeapBase> previewBuffer;
1159
1160 if (mPreviewBuffer == 0) {
1161 mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1162 } else if (size > mPreviewBuffer->virtualSize()) {
1163 mPreviewBuffer.clear();
1164 mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1165 }
1166 if (mPreviewBuffer == 0) {
1167 LOGE("failed to allocate space for preview buffer");
1168 mLock.unlock();
1169 return;
1170 }
1171 previewBuffer = mPreviewBuffer;
1172
1173 memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size);
1174
1175 sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
1176 if (frame == 0) {
1177 LOGE("failed to allocate space for frame callback");
1178 mLock.unlock();
1179 return;
1180 }
1181
1182 mLock.unlock();
1183 client->dataCallback(CAMERA_MSG_PREVIEW_FRAME, frame);
1184}
1185
1186// ----------------------------------------------------------------------------
1187
1188static const int kDumpLockRetries = 50;
1189static const int kDumpLockSleep = 60000;
1190
1191static bool tryLock(Mutex& mutex)
1192{
1193 bool locked = false;
1194 for (int i = 0; i < kDumpLockRetries; ++i) {
1195 if (mutex.tryLock() == NO_ERROR) {
1196 locked = true;
1197 break;
1198 }
1199 usleep(kDumpLockSleep);
1200 }
1201 return locked;
1202}
1203
1204status_t CameraService::dump(int fd, const Vector<String16>& args) {
1205 static const char* kDeadlockedString = "CameraService may be deadlocked\n";
1206
1207 const size_t SIZE = 256;
1208 char buffer[SIZE];
1209 String8 result;
1210 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1211 snprintf(buffer, SIZE, "Permission Denial: "
1212 "can't dump CameraService from pid=%d, uid=%d\n",
1213 getCallingPid(),
1214 getCallingUid());
1215 result.append(buffer);
1216 write(fd, result.string(), result.size());
1217 } else {
1218 bool locked = tryLock(mServiceLock);
1219 // failed to lock - CameraService is probably deadlocked
1220 if (!locked) {
1221 String8 result(kDeadlockedString);
1222 write(fd, result.string(), result.size());
1223 }
1224
1225 bool hasClient = false;
1226 for (int i = 0; i < mNumberOfCameras; i++) {
1227 sp<Client> client = mClient[i].promote();
1228 if (client == 0) continue;
1229 hasClient = true;
1230 sprintf(buffer, "Client[%d] (%p) PID: %d\n",
1231 i,
1232 client->getCameraClient()->asBinder().get(),
1233 client->mClientPid);
1234 result.append(buffer);
1235 write(fd, result.string(), result.size());
1236 client->mHardware->dump(fd, args);
1237 }
1238 if (!hasClient) {
1239 result.append("No camera client yet.\n");
1240 write(fd, result.string(), result.size());
1241 }
1242
1243 if (locked) mServiceLock.unlock();
1244
1245 // change logging level
1246 int n = args.size();
1247 for (int i = 0; i + 1 < n; i++) {
1248 if (args[i] == String16("-v")) {
1249 String8 levelStr(args[i+1]);
1250 int level = atoi(levelStr.string());
1251 sprintf(buffer, "Set Log Level to %d", level);
1252 result.append(buffer);
1253 setLogLevel(level);
1254 }
1255 }
1256 }
1257 return NO_ERROR;
1258}
1259
Jamie Gennis4b791682010-08-10 16:37:53 -07001260sp<ISurface> CameraService::getISurface(const sp<Surface>& surface) {
1261 if (surface != 0) {
1262 return surface->getISurface();
1263 } else {
1264 return sp<ISurface>(0);
1265 }
1266}
1267
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268}; // namespace android