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