CameraService.cpp revision bfa33aae4f54c0020a0568b16a3acb7b30b6ca3d
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(AudioSystem::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(AudioSystem::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    // asBinder() is safe on NULL (returns NULL)
476    if (getISurface(surface)->asBinder() == mSurface) {
477        return result;
478    }
479
480    if (mSurface != 0) {
481        LOG1("clearing old preview surface %p", mSurface.get());
482    }
483    mSurface = getISurface(surface)->asBinder();
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
669int32_t CameraService::Client::getNumberOfVideoBuffers() const {
670    LOG1("getNumberOfVideoBuffers");
671    Mutex::Autolock lock(mLock);
672    if (checkPidAndHardware() != NO_ERROR) return 0;
673    return mHardware->getNumberOfVideoBuffers();
674}
675
676sp<IMemory> CameraService::Client::getVideoBuffer(int32_t index) const {
677    LOG1("getVideoBuffer: %d", index);
678    Mutex::Autolock lock(mLock);
679    if (checkPidAndHardware() != NO_ERROR) return 0;
680    return mHardware->getVideoBuffer(index);
681}
682
683status_t CameraService::Client::storeMetaDataInBuffers(bool enabled)
684{
685    LOG1("storeMetaDataInBuffers: %s", enabled? "true": "false");
686    Mutex::Autolock lock(mLock);
687    if (checkPidAndHardware() != NO_ERROR) {
688        return UNKNOWN_ERROR;
689    }
690    return mHardware->storeMetaDataInBuffers(enabled);
691}
692
693bool CameraService::Client::previewEnabled() {
694    LOG1("previewEnabled (pid %d)", getCallingPid());
695
696    Mutex::Autolock lock(mLock);
697    if (checkPidAndHardware() != NO_ERROR) return false;
698    return mHardware->previewEnabled();
699}
700
701bool CameraService::Client::recordingEnabled() {
702    LOG1("recordingEnabled (pid %d)", getCallingPid());
703
704    Mutex::Autolock lock(mLock);
705    if (checkPidAndHardware() != NO_ERROR) return false;
706    return mHardware->recordingEnabled();
707}
708
709status_t CameraService::Client::autoFocus() {
710    LOG1("autoFocus (pid %d)", getCallingPid());
711
712    Mutex::Autolock lock(mLock);
713    status_t result = checkPidAndHardware();
714    if (result != NO_ERROR) return result;
715
716    return mHardware->autoFocus();
717}
718
719status_t CameraService::Client::cancelAutoFocus() {
720    LOG1("cancelAutoFocus (pid %d)", getCallingPid());
721
722    Mutex::Autolock lock(mLock);
723    status_t result = checkPidAndHardware();
724    if (result != NO_ERROR) return result;
725
726    return mHardware->cancelAutoFocus();
727}
728
729// take a picture - image is returned in callback
730status_t CameraService::Client::takePicture() {
731    LOG1("takePicture (pid %d)", getCallingPid());
732
733    Mutex::Autolock lock(mLock);
734    status_t result = checkPidAndHardware();
735    if (result != NO_ERROR) return result;
736
737    enableMsgType(CAMERA_MSG_SHUTTER |
738                  CAMERA_MSG_POSTVIEW_FRAME |
739                  CAMERA_MSG_RAW_IMAGE |
740                  CAMERA_MSG_COMPRESSED_IMAGE);
741
742    return mHardware->takePicture();
743}
744
745// set preview/capture parameters - key/value pairs
746status_t CameraService::Client::setParameters(const String8& params) {
747    LOG1("setParameters (pid %d) (%s)", getCallingPid(), params.string());
748
749    Mutex::Autolock lock(mLock);
750    status_t result = checkPidAndHardware();
751    if (result != NO_ERROR) return result;
752
753    CameraParameters p(params);
754    return mHardware->setParameters(p);
755}
756
757// get preview/capture parameters - key/value pairs
758String8 CameraService::Client::getParameters() const {
759    Mutex::Autolock lock(mLock);
760    if (checkPidAndHardware() != NO_ERROR) return String8();
761
762    String8 params(mHardware->getParameters().flatten());
763    LOG1("getParameters (pid %d) (%s)", getCallingPid(), params.string());
764    return params;
765}
766
767// enable shutter sound
768status_t CameraService::Client::enableShutterSound(bool enable) {
769    LOG1("enableShutterSound (pid %d)", getCallingPid());
770
771    status_t result = checkPidAndHardware();
772    if (result != NO_ERROR) return result;
773
774    if (enable) {
775        mPlayShutterSound = true;
776        return OK;
777    }
778
779    // Disabling shutter sound may not be allowed. In that case only
780    // allow the mediaserver process to disable the sound.
781    char value[PROPERTY_VALUE_MAX];
782    property_get("ro.camera.sound.forced", value, "0");
783    if (strcmp(value, "0") != 0) {
784        // Disabling shutter sound is not allowed. Deny if the current
785        // process is not mediaserver.
786        if (getCallingPid() != getpid()) {
787            LOGE("Failed to disable shutter sound. Permission denied (pid %d)", getCallingPid());
788            return PERMISSION_DENIED;
789        }
790    }
791
792    mPlayShutterSound = false;
793    return OK;
794}
795
796status_t CameraService::Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) {
797    LOG1("sendCommand (pid %d)", getCallingPid());
798    int orientation;
799    Mutex::Autolock lock(mLock);
800    status_t result = checkPidAndHardware();
801    if (result != NO_ERROR) return result;
802
803    if (cmd == CAMERA_CMD_SET_DISPLAY_ORIENTATION) {
804        // The orientation cannot be set during preview.
805        if (mHardware->previewEnabled()) {
806            return INVALID_OPERATION;
807        }
808        // Mirror the preview if the camera is front-facing.
809        orientation = getOrientation(arg1, mCameraFacing == CAMERA_FACING_FRONT);
810        if (orientation == -1) return BAD_VALUE;
811
812        if (mOrientation != orientation) {
813            mOrientation = orientation;
814        }
815        return OK;
816    } else if (cmd == CAMERA_CMD_ENABLE_SHUTTER_SOUND) {
817        switch (arg1) {
818            case 0:
819                enableShutterSound(false);
820                break;
821            case 1:
822                enableShutterSound(true);
823                break;
824            default:
825                return BAD_VALUE;
826        }
827        return OK;
828    } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) {
829        mCameraService->playSound(SOUND_RECORDING);
830    }
831
832    return mHardware->sendCommand(cmd, arg1, arg2);
833}
834
835// ----------------------------------------------------------------------------
836
837void CameraService::Client::enableMsgType(int32_t msgType) {
838    android_atomic_or(msgType, &mMsgEnabled);
839    mHardware->enableMsgType(msgType);
840}
841
842void CameraService::Client::disableMsgType(int32_t msgType) {
843    android_atomic_and(~msgType, &mMsgEnabled);
844    mHardware->disableMsgType(msgType);
845}
846
847#define CHECK_MESSAGE_INTERVAL 10 // 10ms
848bool CameraService::Client::lockIfMessageWanted(int32_t msgType) {
849    int sleepCount = 0;
850    while (mMsgEnabled & msgType) {
851        if (mLock.tryLock() == NO_ERROR) {
852            if (sleepCount > 0) {
853                LOG1("lockIfMessageWanted(%d): waited for %d ms",
854                    msgType, sleepCount * CHECK_MESSAGE_INTERVAL);
855            }
856            return true;
857        }
858        if (sleepCount++ == 0) {
859            LOG1("lockIfMessageWanted(%d): enter sleep", msgType);
860        }
861        usleep(CHECK_MESSAGE_INTERVAL * 1000);
862    }
863    LOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType);
864    return false;
865}
866
867// ----------------------------------------------------------------------------
868
869// Converts from a raw pointer to the client to a strong pointer during a
870// hardware callback. This requires the callbacks only happen when the client
871// is still alive.
872sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
873    sp<Client> client = gCameraService->getClientById((int) user);
874
875    // This could happen if the Client is in the process of shutting down (the
876    // last strong reference is gone, but the destructor hasn't finished
877    // stopping the hardware).
878    if (client == 0) return NULL;
879
880    // The checks below are not necessary and are for debugging only.
881    if (client->mCameraService.get() != gCameraService) {
882        LOGE("mismatch service!");
883        return NULL;
884    }
885
886    if (client->mHardware == 0) {
887        LOGE("mHardware == 0: callback after disconnect()?");
888        return NULL;
889    }
890
891    return client;
892}
893
894// Callback messages can be dispatched to internal handlers or pass to our
895// client's callback functions, depending on the message type.
896//
897// notifyCallback:
898//      CAMERA_MSG_SHUTTER              handleShutter
899//      (others)                        c->notifyCallback
900// dataCallback:
901//      CAMERA_MSG_PREVIEW_FRAME        handlePreviewData
902//      CAMERA_MSG_POSTVIEW_FRAME       handlePostview
903//      CAMERA_MSG_RAW_IMAGE            handleRawPicture
904//      CAMERA_MSG_COMPRESSED_IMAGE     handleCompressedPicture
905//      (others)                        c->dataCallback
906// dataCallbackTimestamp
907//      (others)                        c->dataCallbackTimestamp
908//
909// NOTE: the *Callback functions grab mLock of the client before passing
910// control to handle* functions. So the handle* functions must release the
911// lock before calling the ICameraClient's callbacks, so those callbacks can
912// invoke methods in the Client class again (For example, the preview frame
913// callback may want to releaseRecordingFrame). The handle* functions must
914// release the lock after all accesses to member variables, so it must be
915// handled very carefully.
916
917void CameraService::Client::notifyCallback(int32_t msgType, int32_t ext1,
918        int32_t ext2, void* user) {
919    LOG2("notifyCallback(%d)", msgType);
920
921    sp<Client> client = getClientFromCookie(user);
922    if (client == 0) return;
923    if (!client->lockIfMessageWanted(msgType)) return;
924
925    switch (msgType) {
926        case CAMERA_MSG_SHUTTER:
927            // ext1 is the dimension of the yuv picture.
928            client->handleShutter((image_rect_type *)ext1);
929            break;
930        default:
931            client->handleGenericNotify(msgType, ext1, ext2);
932            break;
933    }
934}
935
936void CameraService::Client::dataCallback(int32_t msgType,
937        const sp<IMemory>& dataPtr, void* user) {
938    LOG2("dataCallback(%d)", msgType);
939
940    sp<Client> client = getClientFromCookie(user);
941    if (client == 0) return;
942    if (!client->lockIfMessageWanted(msgType)) return;
943
944    if (dataPtr == 0) {
945        LOGE("Null data returned in data callback");
946        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
947        return;
948    }
949
950    switch (msgType) {
951        case CAMERA_MSG_PREVIEW_FRAME:
952            client->handlePreviewData(dataPtr);
953            break;
954        case CAMERA_MSG_POSTVIEW_FRAME:
955            client->handlePostview(dataPtr);
956            break;
957        case CAMERA_MSG_RAW_IMAGE:
958            client->handleRawPicture(dataPtr);
959            break;
960        case CAMERA_MSG_COMPRESSED_IMAGE:
961            client->handleCompressedPicture(dataPtr);
962            break;
963        default:
964            client->handleGenericData(msgType, dataPtr);
965            break;
966    }
967}
968
969void CameraService::Client::dataCallbackTimestamp(nsecs_t timestamp,
970        int32_t msgType, const sp<IMemory>& dataPtr, void* user) {
971    LOG2("dataCallbackTimestamp(%d)", msgType);
972
973    sp<Client> client = getClientFromCookie(user);
974    if (client == 0) return;
975    if (!client->lockIfMessageWanted(msgType)) return;
976
977    if (dataPtr == 0) {
978        LOGE("Null data returned in data with timestamp callback");
979        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
980        return;
981    }
982
983    client->handleGenericDataTimestamp(timestamp, msgType, dataPtr);
984}
985
986// snapshot taken callback
987// "size" is the width and height of yuv picture for registerBuffer.
988// If it is NULL, use the picture size from parameters.
989void CameraService::Client::handleShutter(image_rect_type *size) {
990    if (mPlayShutterSound) {
991        mCameraService->playSound(SOUND_SHUTTER);
992    }
993
994    sp<ICameraClient> c = mCameraClient;
995    if (c != 0) {
996        mLock.unlock();
997        c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0);
998        if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return;
999    }
1000    disableMsgType(CAMERA_MSG_SHUTTER);
1001
1002    mLock.unlock();
1003}
1004
1005// preview callback - frame buffer update
1006void CameraService::Client::handlePreviewData(const sp<IMemory>& mem) {
1007    ssize_t offset;
1008    size_t size;
1009    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1010
1011    // local copy of the callback flags
1012    int flags = mPreviewCallbackFlag;
1013
1014    // is callback enabled?
1015    if (!(flags & FRAME_CALLBACK_FLAG_ENABLE_MASK)) {
1016        // If the enable bit is off, the copy-out and one-shot bits are ignored
1017        LOG2("frame callback is disabled");
1018        mLock.unlock();
1019        return;
1020    }
1021
1022    // hold a strong pointer to the client
1023    sp<ICameraClient> c = mCameraClient;
1024
1025    // clear callback flags if no client or one-shot mode
1026    if (c == 0 || (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) {
1027        LOG2("Disable preview callback");
1028        mPreviewCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK |
1029                                  FRAME_CALLBACK_FLAG_COPY_OUT_MASK |
1030                                  FRAME_CALLBACK_FLAG_ENABLE_MASK);
1031        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
1032    }
1033
1034    if (c != 0) {
1035        // Is the received frame copied out or not?
1036        if (flags & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) {
1037            LOG2("frame is copied");
1038            copyFrameAndPostCopiedFrame(c, heap, offset, size);
1039        } else {
1040            LOG2("frame is forwarded");
1041            mLock.unlock();
1042            c->dataCallback(CAMERA_MSG_PREVIEW_FRAME, mem);
1043        }
1044    } else {
1045        mLock.unlock();
1046    }
1047}
1048
1049// picture callback - postview image ready
1050void CameraService::Client::handlePostview(const sp<IMemory>& mem) {
1051    disableMsgType(CAMERA_MSG_POSTVIEW_FRAME);
1052
1053    sp<ICameraClient> c = mCameraClient;
1054    mLock.unlock();
1055    if (c != 0) {
1056        c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem);
1057    }
1058}
1059
1060// picture callback - raw image ready
1061void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) {
1062    disableMsgType(CAMERA_MSG_RAW_IMAGE);
1063
1064    ssize_t offset;
1065    size_t size;
1066    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1067
1068    sp<ICameraClient> c = mCameraClient;
1069    mLock.unlock();
1070    if (c != 0) {
1071        c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem);
1072    }
1073}
1074
1075// picture callback - compressed picture ready
1076void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) {
1077    disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
1078
1079    sp<ICameraClient> c = mCameraClient;
1080    mLock.unlock();
1081    if (c != 0) {
1082        c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem);
1083    }
1084}
1085
1086
1087void CameraService::Client::handleGenericNotify(int32_t msgType,
1088    int32_t ext1, int32_t ext2) {
1089    sp<ICameraClient> c = mCameraClient;
1090    mLock.unlock();
1091    if (c != 0) {
1092        c->notifyCallback(msgType, ext1, ext2);
1093    }
1094}
1095
1096void CameraService::Client::handleGenericData(int32_t msgType,
1097    const sp<IMemory>& dataPtr) {
1098    sp<ICameraClient> c = mCameraClient;
1099    mLock.unlock();
1100    if (c != 0) {
1101        c->dataCallback(msgType, dataPtr);
1102    }
1103}
1104
1105void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp,
1106    int32_t msgType, const sp<IMemory>& dataPtr) {
1107    sp<ICameraClient> c = mCameraClient;
1108    mLock.unlock();
1109    if (c != 0) {
1110        c->dataCallbackTimestamp(timestamp, msgType, dataPtr);
1111    }
1112}
1113
1114void CameraService::Client::copyFrameAndPostCopiedFrame(
1115        const sp<ICameraClient>& client, const sp<IMemoryHeap>& heap,
1116        size_t offset, size_t size) {
1117    LOG2("copyFrameAndPostCopiedFrame");
1118    // It is necessary to copy out of pmem before sending this to
1119    // the callback. For efficiency, reuse the same MemoryHeapBase
1120    // provided it's big enough. Don't allocate the memory or
1121    // perform the copy if there's no callback.
1122    // hold the preview lock while we grab a reference to the preview buffer
1123    sp<MemoryHeapBase> previewBuffer;
1124
1125    if (mPreviewBuffer == 0) {
1126        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1127    } else if (size > mPreviewBuffer->virtualSize()) {
1128        mPreviewBuffer.clear();
1129        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1130    }
1131    if (mPreviewBuffer == 0) {
1132        LOGE("failed to allocate space for preview buffer");
1133        mLock.unlock();
1134        return;
1135    }
1136    previewBuffer = mPreviewBuffer;
1137
1138    memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size);
1139
1140    sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
1141    if (frame == 0) {
1142        LOGE("failed to allocate space for frame callback");
1143        mLock.unlock();
1144        return;
1145    }
1146
1147    mLock.unlock();
1148    client->dataCallback(CAMERA_MSG_PREVIEW_FRAME, frame);
1149}
1150
1151int CameraService::Client::getOrientation(int degrees, bool mirror) {
1152    if (!mirror) {
1153        if (degrees == 0) return 0;
1154        else if (degrees == 90) return HAL_TRANSFORM_ROT_90;
1155        else if (degrees == 180) return HAL_TRANSFORM_ROT_180;
1156        else if (degrees == 270) return HAL_TRANSFORM_ROT_270;
1157    } else {  // Do mirror (horizontal flip)
1158        if (degrees == 0) {           // FLIP_H and ROT_0
1159            return HAL_TRANSFORM_FLIP_H;
1160        } else if (degrees == 90) {   // FLIP_H and ROT_90
1161            return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
1162        } else if (degrees == 180) {  // FLIP_H and ROT_180
1163            return HAL_TRANSFORM_FLIP_V;
1164        } else if (degrees == 270) {  // FLIP_H and ROT_270
1165            return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
1166        }
1167    }
1168    LOGE("Invalid setDisplayOrientation degrees=%d", degrees);
1169    return -1;
1170}
1171
1172
1173// ----------------------------------------------------------------------------
1174
1175static const int kDumpLockRetries = 50;
1176static const int kDumpLockSleep = 60000;
1177
1178static bool tryLock(Mutex& mutex)
1179{
1180    bool locked = false;
1181    for (int i = 0; i < kDumpLockRetries; ++i) {
1182        if (mutex.tryLock() == NO_ERROR) {
1183            locked = true;
1184            break;
1185        }
1186        usleep(kDumpLockSleep);
1187    }
1188    return locked;
1189}
1190
1191status_t CameraService::dump(int fd, const Vector<String16>& args) {
1192    static const char* kDeadlockedString = "CameraService may be deadlocked\n";
1193
1194    const size_t SIZE = 256;
1195    char buffer[SIZE];
1196    String8 result;
1197    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1198        snprintf(buffer, SIZE, "Permission Denial: "
1199                "can't dump CameraService from pid=%d, uid=%d\n",
1200                getCallingPid(),
1201                getCallingUid());
1202        result.append(buffer);
1203        write(fd, result.string(), result.size());
1204    } else {
1205        bool locked = tryLock(mServiceLock);
1206        // failed to lock - CameraService is probably deadlocked
1207        if (!locked) {
1208            String8 result(kDeadlockedString);
1209            write(fd, result.string(), result.size());
1210        }
1211
1212        bool hasClient = false;
1213        for (int i = 0; i < mNumberOfCameras; i++) {
1214            sp<Client> client = mClient[i].promote();
1215            if (client == 0) continue;
1216            hasClient = true;
1217            sprintf(buffer, "Client[%d] (%p) PID: %d\n",
1218                    i,
1219                    client->getCameraClient()->asBinder().get(),
1220                    client->mClientPid);
1221            result.append(buffer);
1222            write(fd, result.string(), result.size());
1223            client->mHardware->dump(fd, args);
1224        }
1225        if (!hasClient) {
1226            result.append("No camera client yet.\n");
1227            write(fd, result.string(), result.size());
1228        }
1229
1230        if (locked) mServiceLock.unlock();
1231
1232        // change logging level
1233        int n = args.size();
1234        for (int i = 0; i + 1 < n; i++) {
1235            if (args[i] == String16("-v")) {
1236                String8 levelStr(args[i+1]);
1237                int level = atoi(levelStr.string());
1238                sprintf(buffer, "Set Log Level to %d", level);
1239                result.append(buffer);
1240                setLogLevel(level);
1241            }
1242        }
1243    }
1244    return NO_ERROR;
1245}
1246
1247sp<ISurface> CameraService::getISurface(const sp<Surface>& surface) {
1248    if (surface != 0) {
1249        return surface->getISurface();
1250    } else {
1251        return sp<ISurface>(0);
1252    }
1253}
1254
1255}; // namespace android
1256