CameraService.cpp revision 986ef2ad4c96952711d87af481f3afb40aa10775
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)) return;
937
938    if (dataPtr == 0) {
939        LOGE("Null data returned in data with timestamp callback");
940        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
941        return;
942    }
943
944    client->handleGenericDataTimestamp(timestamp, msgType, dataPtr);
945}
946
947// snapshot taken callback
948// "size" is the width and height of yuv picture for registerBuffer.
949// If it is NULL, use the picture size from parameters.
950void CameraService::Client::handleShutter(image_rect_type *size) {
951    if (mPlayShutterSound) {
952        mCameraService->playSound(SOUND_SHUTTER);
953    }
954
955    sp<ICameraClient> c = mCameraClient;
956    if (c != 0) {
957        mLock.unlock();
958        c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0);
959        if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return;
960    }
961    disableMsgType(CAMERA_MSG_SHUTTER);
962
963    // It takes some time before yuvPicture callback to be called.
964    // Register the buffer for raw image here to reduce latency.
965    if (mSurface != 0) {
966        int w, h;
967        CameraParameters params(mHardware->getParameters());
968        if (size == NULL) {
969            params.getPictureSize(&w, &h);
970        } else {
971            w = size->width;
972            h = size->height;
973            w &= ~1;
974            h &= ~1;
975            LOG1("Snapshot image width=%d, height=%d", w, h);
976        }
977        IPCThreadState::self()->flushCommands();
978    }
979
980    mLock.unlock();
981}
982
983// preview callback - frame buffer update
984void CameraService::Client::handlePreviewData(const sp<IMemory>& mem) {
985    ssize_t offset;
986    size_t size;
987    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
988
989    // local copy of the callback flags
990    int flags = mPreviewCallbackFlag;
991
992    // is callback enabled?
993    if (!(flags & FRAME_CALLBACK_FLAG_ENABLE_MASK)) {
994        // If the enable bit is off, the copy-out and one-shot bits are ignored
995        LOG2("frame callback is disabled");
996        mLock.unlock();
997        return;
998    }
999
1000    // hold a strong pointer to the client
1001    sp<ICameraClient> c = mCameraClient;
1002
1003    // clear callback flags if no client or one-shot mode
1004    if (c == 0 || (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) {
1005        LOG2("Disable preview callback");
1006        mPreviewCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK |
1007                                  FRAME_CALLBACK_FLAG_COPY_OUT_MASK |
1008                                  FRAME_CALLBACK_FLAG_ENABLE_MASK);
1009        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
1010    }
1011
1012    if (c != 0) {
1013        // Is the received frame copied out or not?
1014        if (flags & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) {
1015            LOG2("frame is copied");
1016            copyFrameAndPostCopiedFrame(c, heap, offset, size);
1017        } else {
1018            LOG2("frame is forwarded");
1019            mLock.unlock();
1020            c->dataCallback(CAMERA_MSG_PREVIEW_FRAME, mem);
1021        }
1022    } else {
1023        mLock.unlock();
1024    }
1025}
1026
1027// picture callback - postview image ready
1028void CameraService::Client::handlePostview(const sp<IMemory>& mem) {
1029    disableMsgType(CAMERA_MSG_POSTVIEW_FRAME);
1030
1031    sp<ICameraClient> c = mCameraClient;
1032    mLock.unlock();
1033    if (c != 0) {
1034        c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem);
1035    }
1036}
1037
1038// picture callback - raw image ready
1039void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) {
1040    disableMsgType(CAMERA_MSG_RAW_IMAGE);
1041
1042    ssize_t offset;
1043    size_t size;
1044    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1045
1046    sp<ICameraClient> c = mCameraClient;
1047    mLock.unlock();
1048    if (c != 0) {
1049        c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem);
1050    }
1051}
1052
1053// picture callback - compressed picture ready
1054void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) {
1055    disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
1056
1057    sp<ICameraClient> c = mCameraClient;
1058    mLock.unlock();
1059    if (c != 0) {
1060        c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem);
1061    }
1062}
1063
1064
1065void CameraService::Client::handleGenericNotify(int32_t msgType,
1066    int32_t ext1, int32_t ext2) {
1067    sp<ICameraClient> c = mCameraClient;
1068    mLock.unlock();
1069    if (c != 0) {
1070        c->notifyCallback(msgType, ext1, ext2);
1071    }
1072}
1073
1074void CameraService::Client::handleGenericData(int32_t msgType,
1075    const sp<IMemory>& dataPtr) {
1076    sp<ICameraClient> c = mCameraClient;
1077    mLock.unlock();
1078    if (c != 0) {
1079        c->dataCallback(msgType, dataPtr);
1080    }
1081}
1082
1083void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp,
1084    int32_t msgType, const sp<IMemory>& dataPtr) {
1085    sp<ICameraClient> c = mCameraClient;
1086    mLock.unlock();
1087    if (c != 0) {
1088        c->dataCallbackTimestamp(timestamp, msgType, dataPtr);
1089    }
1090}
1091
1092void CameraService::Client::copyFrameAndPostCopiedFrame(
1093        const sp<ICameraClient>& client, const sp<IMemoryHeap>& heap,
1094        size_t offset, size_t size) {
1095    LOG2("copyFrameAndPostCopiedFrame");
1096    // It is necessary to copy out of pmem before sending this to
1097    // the callback. For efficiency, reuse the same MemoryHeapBase
1098    // provided it's big enough. Don't allocate the memory or
1099    // perform the copy if there's no callback.
1100    // hold the preview lock while we grab a reference to the preview buffer
1101    sp<MemoryHeapBase> previewBuffer;
1102
1103    if (mPreviewBuffer == 0) {
1104        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1105    } else if (size > mPreviewBuffer->virtualSize()) {
1106        mPreviewBuffer.clear();
1107        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1108    }
1109    if (mPreviewBuffer == 0) {
1110        LOGE("failed to allocate space for preview buffer");
1111        mLock.unlock();
1112        return;
1113    }
1114    previewBuffer = mPreviewBuffer;
1115
1116    memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size);
1117
1118    sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
1119    if (frame == 0) {
1120        LOGE("failed to allocate space for frame callback");
1121        mLock.unlock();
1122        return;
1123    }
1124
1125    mLock.unlock();
1126    client->dataCallback(CAMERA_MSG_PREVIEW_FRAME, frame);
1127}
1128
1129int CameraService::Client::getOrientation(int degrees, bool mirror) {
1130    if (!mirror) {
1131        if (degrees == 0) return 0;
1132        else if (degrees == 90) return HAL_TRANSFORM_ROT_90;
1133        else if (degrees == 180) return HAL_TRANSFORM_ROT_180;
1134        else if (degrees == 270) return HAL_TRANSFORM_ROT_270;
1135    } else {  // Do mirror (horizontal flip)
1136        if (degrees == 0) {           // FLIP_H and ROT_0
1137            return HAL_TRANSFORM_FLIP_H;
1138        } else if (degrees == 90) {   // FLIP_H and ROT_90
1139            return HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
1140        } else if (degrees == 180) {  // FLIP_H and ROT_180
1141            return HAL_TRANSFORM_FLIP_V;
1142        } else if (degrees == 270) {  // FLIP_H and ROT_270
1143            return HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
1144        }
1145    }
1146    LOGE("Invalid setDisplayOrientation degrees=%d", degrees);
1147    return -1;
1148}
1149
1150
1151// ----------------------------------------------------------------------------
1152
1153static const int kDumpLockRetries = 50;
1154static const int kDumpLockSleep = 60000;
1155
1156static bool tryLock(Mutex& mutex)
1157{
1158    bool locked = false;
1159    for (int i = 0; i < kDumpLockRetries; ++i) {
1160        if (mutex.tryLock() == NO_ERROR) {
1161            locked = true;
1162            break;
1163        }
1164        usleep(kDumpLockSleep);
1165    }
1166    return locked;
1167}
1168
1169status_t CameraService::dump(int fd, const Vector<String16>& args) {
1170    static const char* kDeadlockedString = "CameraService may be deadlocked\n";
1171
1172    const size_t SIZE = 256;
1173    char buffer[SIZE];
1174    String8 result;
1175    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1176        snprintf(buffer, SIZE, "Permission Denial: "
1177                "can't dump CameraService from pid=%d, uid=%d\n",
1178                getCallingPid(),
1179                getCallingUid());
1180        result.append(buffer);
1181        write(fd, result.string(), result.size());
1182    } else {
1183        bool locked = tryLock(mServiceLock);
1184        // failed to lock - CameraService is probably deadlocked
1185        if (!locked) {
1186            String8 result(kDeadlockedString);
1187            write(fd, result.string(), result.size());
1188        }
1189
1190        bool hasClient = false;
1191        for (int i = 0; i < mNumberOfCameras; i++) {
1192            sp<Client> client = mClient[i].promote();
1193            if (client == 0) continue;
1194            hasClient = true;
1195            sprintf(buffer, "Client[%d] (%p) PID: %d\n",
1196                    i,
1197                    client->getCameraClient()->asBinder().get(),
1198                    client->mClientPid);
1199            result.append(buffer);
1200            write(fd, result.string(), result.size());
1201            client->mHardware->dump(fd, args);
1202        }
1203        if (!hasClient) {
1204            result.append("No camera client yet.\n");
1205            write(fd, result.string(), result.size());
1206        }
1207
1208        if (locked) mServiceLock.unlock();
1209
1210        // change logging level
1211        int n = args.size();
1212        for (int i = 0; i + 1 < n; i++) {
1213            if (args[i] == String16("-v")) {
1214                String8 levelStr(args[i+1]);
1215                int level = atoi(levelStr.string());
1216                sprintf(buffer, "Set Log Level to %d", level);
1217                result.append(buffer);
1218                setLogLevel(level);
1219            }
1220        }
1221    }
1222    return NO_ERROR;
1223}
1224
1225sp<ISurface> CameraService::getISurface(const sp<Surface>& surface) {
1226    if (surface != 0) {
1227        return surface->getISurface();
1228    } else {
1229        return sp<ISurface>(0);
1230    }
1231}
1232
1233}; // namespace android
1234