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