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