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