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