CameraService.cpp revision b36f2df1daf7e733be7c51f93792f8fc4252544c
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
308    mHardware->setCallbacks(notifyCallback,
309                            dataCallback,
310                            dataCallbackTimestamp,
311                            (void *)cameraId);
312
313    // Enable zoom, error, and focus messages by default
314    enableMsgType(CAMERA_MSG_ERROR |
315                  CAMERA_MSG_ZOOM |
316                  CAMERA_MSG_FOCUS);
317    mOverlayW = 0;
318    mOverlayH = 0;
319
320    // Callback is disabled by default
321    mPreviewCallbackFlag = FRAME_CALLBACK_FLAG_NOOP;
322    mOrientation = 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            result = mHardware->setPreviewWindow(mPreviewWindow);
512        }
513    }
514
515    return result;
516}
517
518status_t CameraService::Client::setOverlay() {
519    int w, h;
520    CameraParameters params(mHardware->getParameters());
521    params.getPreviewSize(&w, &h);
522
523    if (w != mOverlayW || h != mOverlayH || mOrientationChanged) {
524        // Force the destruction of any previous overlay
525        sp<Overlay> dummy;
526        mHardware->setOverlay(dummy);
527        mOverlayRef = 0;
528        mOrientationChanged = false;
529    }
530
531    status_t result = NO_ERROR;
532    if (mSurface == 0) {
533        result = mHardware->setOverlay(NULL);
534    } else {
535        if (mOverlayRef == 0) {
536            // FIXME:
537            // Surfaceflinger may hold onto the previous overlay reference for some
538            // time after we try to destroy it. retry a few times. In the future, we
539            // should make the destroy call block, or possibly specify that we can
540            // wait in the createOverlay call if the previous overlay is in the
541            // process of being destroyed.
542            for (int retry = 0; retry < 50; ++retry) {
543                mOverlayRef = mSurface->createOverlay(w, h, OVERLAY_FORMAT_DEFAULT,
544                                                      mOrientation);
545                if (mOverlayRef != 0) break;
546                LOGW("Overlay create failed - retrying");
547                usleep(20000);
548            }
549            if (mOverlayRef == 0) {
550                LOGE("Overlay Creation Failed!");
551                return -EINVAL;
552            }
553            result = mHardware->setOverlay(new Overlay(mOverlayRef));
554        }
555    }
556    if (result != NO_ERROR) {
557        LOGE("mHardware->setOverlay() failed with status %d\n", result);
558        return result;
559    }
560
561    mOverlayW = w;
562    mOverlayH = h;
563
564    return result;
565}
566
567// set the preview callback flag to affect how the received frames from
568// preview are handled.
569void CameraService::Client::setPreviewCallbackFlag(int callback_flag) {
570    LOG1("setPreviewCallbackFlag(%d) (pid %d)", callback_flag, getCallingPid());
571    Mutex::Autolock lock(mLock);
572    if (checkPidAndHardware() != NO_ERROR) return;
573
574    mPreviewCallbackFlag = callback_flag;
575    if (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ENABLE_MASK) {
576        enableMsgType(CAMERA_MSG_PREVIEW_FRAME);
577    } else {
578        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
579    }
580}
581
582// start preview mode
583status_t CameraService::Client::startPreview() {
584    LOG1("startPreview (pid %d)", getCallingPid());
585    return startCameraMode(CAMERA_PREVIEW_MODE);
586}
587
588// start recording mode
589status_t CameraService::Client::startRecording() {
590    LOG1("startRecording (pid %d)", getCallingPid());
591    return startCameraMode(CAMERA_RECORDING_MODE);
592}
593
594// start preview or recording
595status_t CameraService::Client::startCameraMode(camera_mode mode) {
596    LOG1("startCameraMode(%d)", mode);
597    Mutex::Autolock lock(mLock);
598    status_t result = checkPidAndHardware();
599    if (result != NO_ERROR) return result;
600
601    switch(mode) {
602        case CAMERA_PREVIEW_MODE:
603            if (mSurface == 0 && mPreviewWindow == 0) {
604                LOG1("mSurface is not set yet.");
605                // still able to start preview in this case.
606            }
607            return startPreviewMode();
608        case CAMERA_RECORDING_MODE:
609            if (mSurface == 0 && mPreviewWindow == 0) {
610                LOGE("mSurface or mPreviewWindow must be set before startRecordingMode.");
611                return INVALID_OPERATION;
612            }
613            return startRecordingMode();
614        default:
615            return UNKNOWN_ERROR;
616    }
617}
618
619status_t CameraService::Client::startPreviewMode() {
620    LOG1("startPreviewMode");
621    status_t result = NO_ERROR;
622
623    // if preview has been enabled, nothing needs to be done
624    if (mHardware->previewEnabled()) {
625        return NO_ERROR;
626    }
627
628    if (mUseOverlay) {
629        // If preview display has been set, set overlay now.
630        if (mSurface != 0) {
631            result = setOverlay();
632        }
633        if (result != NO_ERROR) return result;
634        result = mHardware->startPreview();
635    } else {
636        // XXX: Set the orientation of the ANativeWindow.
637        mHardware->setPreviewWindow(mPreviewWindow);
638        result = mHardware->startPreview();
639    }
640    return result;
641}
642
643status_t CameraService::Client::startRecordingMode() {
644    LOG1("startRecordingMode");
645    status_t result = NO_ERROR;
646
647    // if recording has been enabled, nothing needs to be done
648    if (mHardware->recordingEnabled()) {
649        return NO_ERROR;
650    }
651
652    // if preview has not been started, start preview first
653    if (!mHardware->previewEnabled()) {
654        result = startPreviewMode();
655        if (result != NO_ERROR) {
656            return result;
657        }
658    }
659
660    // start recording mode
661    enableMsgType(CAMERA_MSG_VIDEO_FRAME);
662    mCameraService->playSound(SOUND_RECORDING);
663    result = mHardware->startRecording();
664    if (result != NO_ERROR) {
665        LOGE("mHardware->startRecording() failed with status %d", result);
666    }
667    return result;
668}
669
670// stop preview mode
671void CameraService::Client::stopPreview() {
672    LOG1("stopPreview (pid %d)", getCallingPid());
673    Mutex::Autolock lock(mLock);
674    if (checkPidAndHardware() != NO_ERROR) return;
675
676
677    disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
678    mHardware->stopPreview();
679
680    mPreviewBuffer.clear();
681}
682
683// stop recording mode
684void CameraService::Client::stopRecording() {
685    LOG1("stopRecording (pid %d)", getCallingPid());
686    Mutex::Autolock lock(mLock);
687    if (checkPidAndHardware() != NO_ERROR) return;
688
689    mCameraService->playSound(SOUND_RECORDING);
690    disableMsgType(CAMERA_MSG_VIDEO_FRAME);
691    mHardware->stopRecording();
692
693    mPreviewBuffer.clear();
694}
695
696// release a recording frame
697void CameraService::Client::releaseRecordingFrame(const sp<IMemory>& mem) {
698    Mutex::Autolock lock(mLock);
699    if (checkPidAndHardware() != NO_ERROR) return;
700    mHardware->releaseRecordingFrame(mem);
701}
702
703bool CameraService::Client::previewEnabled() {
704    LOG1("previewEnabled (pid %d)", getCallingPid());
705
706    Mutex::Autolock lock(mLock);
707    if (checkPidAndHardware() != NO_ERROR) return false;
708    return mHardware->previewEnabled();
709}
710
711bool CameraService::Client::recordingEnabled() {
712    LOG1("recordingEnabled (pid %d)", getCallingPid());
713
714    Mutex::Autolock lock(mLock);
715    if (checkPidAndHardware() != NO_ERROR) return false;
716    return mHardware->recordingEnabled();
717}
718
719status_t CameraService::Client::autoFocus() {
720    LOG1("autoFocus (pid %d)", getCallingPid());
721
722    Mutex::Autolock lock(mLock);
723    status_t result = checkPidAndHardware();
724    if (result != NO_ERROR) return result;
725
726    return mHardware->autoFocus();
727}
728
729status_t CameraService::Client::cancelAutoFocus() {
730    LOG1("cancelAutoFocus (pid %d)", getCallingPid());
731
732    Mutex::Autolock lock(mLock);
733    status_t result = checkPidAndHardware();
734    if (result != NO_ERROR) return result;
735
736    return mHardware->cancelAutoFocus();
737}
738
739// take a picture - image is returned in callback
740status_t CameraService::Client::takePicture() {
741    LOG1("takePicture (pid %d)", getCallingPid());
742
743    Mutex::Autolock lock(mLock);
744    status_t result = checkPidAndHardware();
745    if (result != NO_ERROR) return result;
746
747    enableMsgType(CAMERA_MSG_SHUTTER |
748                  CAMERA_MSG_POSTVIEW_FRAME |
749                  CAMERA_MSG_RAW_IMAGE |
750                  CAMERA_MSG_COMPRESSED_IMAGE);
751
752    return mHardware->takePicture();
753}
754
755// set preview/capture parameters - key/value pairs
756status_t CameraService::Client::setParameters(const String8& params) {
757    LOG1("setParameters (pid %d) (%s)", getCallingPid(), params.string());
758
759    Mutex::Autolock lock(mLock);
760    status_t result = checkPidAndHardware();
761    if (result != NO_ERROR) return result;
762
763    CameraParameters p(params);
764    return mHardware->setParameters(p);
765}
766
767// get preview/capture parameters - key/value pairs
768String8 CameraService::Client::getParameters() const {
769    Mutex::Autolock lock(mLock);
770    if (checkPidAndHardware() != NO_ERROR) return String8();
771
772    String8 params(mHardware->getParameters().flatten());
773    LOG1("getParameters (pid %d) (%s)", getCallingPid(), params.string());
774    return params;
775}
776
777// enable shutter sound
778status_t CameraService::Client::enableShutterSound(bool enable) {
779    LOG1("enableShutterSound (pid %d)", getCallingPid());
780
781    status_t result = checkPidAndHardware();
782    if (result != NO_ERROR) return result;
783
784    if (enable) {
785        mPlayShutterSound = true;
786        return OK;
787    }
788
789    // Disabling shutter sound may not be allowed. In that case only
790    // allow the mediaserver process to disable the sound.
791    char value[PROPERTY_VALUE_MAX];
792    property_get("ro.camera.sound.forced", value, "0");
793    if (strcmp(value, "0") != 0) {
794        // Disabling shutter sound is not allowed. Deny if the current
795        // process is not mediaserver.
796        if (getCallingPid() != getpid()) {
797            LOGE("Failed to disable shutter sound. Permission denied (pid %d)", getCallingPid());
798            return PERMISSION_DENIED;
799        }
800    }
801
802    mPlayShutterSound = false;
803    return OK;
804}
805
806status_t CameraService::Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) {
807    LOG1("sendCommand (pid %d)", getCallingPid());
808    int orientation;
809    Mutex::Autolock lock(mLock);
810    status_t result = checkPidAndHardware();
811    if (result != NO_ERROR) return result;
812
813    if (cmd == CAMERA_CMD_SET_DISPLAY_ORIENTATION) {
814        // The orientation cannot be set during preview.
815        if (mHardware->previewEnabled()) {
816            return INVALID_OPERATION;
817        }
818        switch (arg1) {
819            case 0:
820                orientation = ISurface::BufferHeap::ROT_0;
821                break;
822            case 90:
823                orientation = ISurface::BufferHeap::ROT_90;
824                break;
825            case 180:
826                orientation = ISurface::BufferHeap::ROT_180;
827                break;
828            case 270:
829                orientation = ISurface::BufferHeap::ROT_270;
830                break;
831            default:
832                return BAD_VALUE;
833        }
834        if (mOrientation != orientation) {
835            mOrientation = orientation;
836            if (mOverlayRef != 0) mOrientationChanged = true;
837        }
838        return OK;
839    } else if (cmd == CAMERA_CMD_ENABLE_SHUTTER_SOUND) {
840        switch (arg1) {
841            case 0:
842                enableShutterSound(false);
843                break;
844            case 1:
845                enableShutterSound(true);
846                break;
847            default:
848                return BAD_VALUE;
849        }
850        return OK;
851    } else if (cmd == CAMERA_CMD_PLAY_RECORDING_SOUND) {
852        mCameraService->playSound(SOUND_RECORDING);
853    }
854
855    return mHardware->sendCommand(cmd, arg1, arg2);
856}
857
858// ----------------------------------------------------------------------------
859
860void CameraService::Client::enableMsgType(int32_t msgType) {
861    android_atomic_or(msgType, &mMsgEnabled);
862    mHardware->enableMsgType(msgType);
863}
864
865void CameraService::Client::disableMsgType(int32_t msgType) {
866    android_atomic_and(~msgType, &mMsgEnabled);
867    mHardware->disableMsgType(msgType);
868}
869
870#define CHECK_MESSAGE_INTERVAL 10 // 10ms
871bool CameraService::Client::lockIfMessageWanted(int32_t msgType) {
872    int sleepCount = 0;
873    while (mMsgEnabled & msgType) {
874        if (mLock.tryLock() == NO_ERROR) {
875            if (sleepCount > 0) {
876                LOG1("lockIfMessageWanted(%d): waited for %d ms",
877                    msgType, sleepCount * CHECK_MESSAGE_INTERVAL);
878            }
879            return true;
880        }
881        if (sleepCount++ == 0) {
882            LOG1("lockIfMessageWanted(%d): enter sleep", msgType);
883        }
884        usleep(CHECK_MESSAGE_INTERVAL * 1000);
885    }
886    LOGW("lockIfMessageWanted(%d): dropped unwanted message", msgType);
887    return false;
888}
889
890// ----------------------------------------------------------------------------
891
892// Converts from a raw pointer to the client to a strong pointer during a
893// hardware callback. This requires the callbacks only happen when the client
894// is still alive.
895sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
896    sp<Client> client = gCameraService->getClientById((int) user);
897
898    // This could happen if the Client is in the process of shutting down (the
899    // last strong reference is gone, but the destructor hasn't finished
900    // stopping the hardware).
901    if (client == 0) return NULL;
902
903    // The checks below are not necessary and are for debugging only.
904    if (client->mCameraService.get() != gCameraService) {
905        LOGE("mismatch service!");
906        return NULL;
907    }
908
909    if (client->mHardware == 0) {
910        LOGE("mHardware == 0: callback after disconnect()?");
911        return NULL;
912    }
913
914    return client;
915}
916
917// Callback messages can be dispatched to internal handlers or pass to our
918// client's callback functions, depending on the message type.
919//
920// notifyCallback:
921//      CAMERA_MSG_SHUTTER              handleShutter
922//      (others)                        c->notifyCallback
923// dataCallback:
924//      CAMERA_MSG_PREVIEW_FRAME        handlePreviewData
925//      CAMERA_MSG_POSTVIEW_FRAME       handlePostview
926//      CAMERA_MSG_RAW_IMAGE            handleRawPicture
927//      CAMERA_MSG_COMPRESSED_IMAGE     handleCompressedPicture
928//      (others)                        c->dataCallback
929// dataCallbackTimestamp
930//      (others)                        c->dataCallbackTimestamp
931//
932// NOTE: the *Callback functions grab mLock of the client before passing
933// control to handle* functions. So the handle* functions must release the
934// lock before calling the ICameraClient's callbacks, so those callbacks can
935// invoke methods in the Client class again (For example, the preview frame
936// callback may want to releaseRecordingFrame). The handle* functions must
937// release the lock after all accesses to member variables, so it must be
938// handled very carefully.
939
940void CameraService::Client::notifyCallback(int32_t msgType, int32_t ext1,
941        int32_t ext2, void* user) {
942    LOG2("notifyCallback(%d)", msgType);
943
944    sp<Client> client = getClientFromCookie(user);
945    if (client == 0) return;
946    if (!client->lockIfMessageWanted(msgType)) return;
947
948    switch (msgType) {
949        case CAMERA_MSG_SHUTTER:
950            // ext1 is the dimension of the yuv picture.
951            client->handleShutter((image_rect_type *)ext1);
952            break;
953        default:
954            client->handleGenericNotify(msgType, ext1, ext2);
955            break;
956    }
957}
958
959void CameraService::Client::dataCallback(int32_t msgType,
960        const sp<IMemory>& dataPtr, void* user) {
961    LOG2("dataCallback(%d)", msgType);
962
963    sp<Client> client = getClientFromCookie(user);
964    if (client == 0) return;
965    if (!client->lockIfMessageWanted(msgType)) return;
966
967    if (dataPtr == 0) {
968        LOGE("Null data returned in data callback");
969        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
970        return;
971    }
972
973    switch (msgType) {
974        case CAMERA_MSG_PREVIEW_FRAME:
975            client->handlePreviewData(dataPtr);
976            break;
977        case CAMERA_MSG_POSTVIEW_FRAME:
978            client->handlePostview(dataPtr);
979            break;
980        case CAMERA_MSG_RAW_IMAGE:
981            client->handleRawPicture(dataPtr);
982            break;
983        case CAMERA_MSG_COMPRESSED_IMAGE:
984            client->handleCompressedPicture(dataPtr);
985            break;
986        default:
987            client->handleGenericData(msgType, dataPtr);
988            break;
989    }
990}
991
992void CameraService::Client::dataCallbackTimestamp(nsecs_t timestamp,
993        int32_t msgType, const sp<IMemory>& dataPtr, void* user) {
994    LOG2("dataCallbackTimestamp(%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 with timestamp callback");
1002        client->handleGenericNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0);
1003        return;
1004    }
1005
1006    client->handleGenericDataTimestamp(timestamp, msgType, dataPtr);
1007}
1008
1009// snapshot taken callback
1010// "size" is the width and height of yuv picture for registerBuffer.
1011// If it is NULL, use the picture size from parameters.
1012void CameraService::Client::handleShutter(image_rect_type *size) {
1013    if (mPlayShutterSound) {
1014        mCameraService->playSound(SOUND_SHUTTER);
1015    }
1016
1017    sp<ICameraClient> c = mCameraClient;
1018    if (c != 0) {
1019        mLock.unlock();
1020        c->notifyCallback(CAMERA_MSG_SHUTTER, 0, 0);
1021        if (!lockIfMessageWanted(CAMERA_MSG_SHUTTER)) return;
1022    }
1023    disableMsgType(CAMERA_MSG_SHUTTER);
1024
1025    // It takes some time before yuvPicture callback to be called.
1026    // Register the buffer for raw image here to reduce latency.
1027    if (mSurface != 0 && !mUseOverlay) {
1028        int w, h;
1029        CameraParameters params(mHardware->getParameters());
1030        if (size == NULL) {
1031            params.getPictureSize(&w, &h);
1032        } else {
1033            w = size->width;
1034            h = size->height;
1035            w &= ~1;
1036            h &= ~1;
1037            LOG1("Snapshot image width=%d, height=%d", w, h);
1038        }
1039        // FIXME: don't use hardcoded format constants here
1040        ISurface::BufferHeap buffers(w, h, w, h,
1041            HAL_PIXEL_FORMAT_YCrCb_420_SP, mOrientation, 0,
1042            mHardware->getRawHeap());
1043
1044        IPCThreadState::self()->flushCommands();
1045    }
1046
1047    mLock.unlock();
1048}
1049
1050// preview callback - frame buffer update
1051void CameraService::Client::handlePreviewData(const sp<IMemory>& mem) {
1052    ssize_t offset;
1053    size_t size;
1054    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1055
1056    // local copy of the callback flags
1057    int flags = mPreviewCallbackFlag;
1058
1059    // is callback enabled?
1060    if (!(flags & FRAME_CALLBACK_FLAG_ENABLE_MASK)) {
1061        // If the enable bit is off, the copy-out and one-shot bits are ignored
1062        LOG2("frame callback is disabled");
1063        mLock.unlock();
1064        return;
1065    }
1066
1067    // hold a strong pointer to the client
1068    sp<ICameraClient> c = mCameraClient;
1069
1070    // clear callback flags if no client or one-shot mode
1071    if (c == 0 || (mPreviewCallbackFlag & FRAME_CALLBACK_FLAG_ONE_SHOT_MASK)) {
1072        LOG2("Disable preview callback");
1073        mPreviewCallbackFlag &= ~(FRAME_CALLBACK_FLAG_ONE_SHOT_MASK |
1074                                  FRAME_CALLBACK_FLAG_COPY_OUT_MASK |
1075                                  FRAME_CALLBACK_FLAG_ENABLE_MASK);
1076        disableMsgType(CAMERA_MSG_PREVIEW_FRAME);
1077    }
1078
1079    if (c != 0) {
1080        // Is the received frame copied out or not?
1081        if (flags & FRAME_CALLBACK_FLAG_COPY_OUT_MASK) {
1082            LOG2("frame is copied");
1083            copyFrameAndPostCopiedFrame(c, heap, offset, size);
1084        } else {
1085            LOG2("frame is forwarded");
1086            mLock.unlock();
1087            c->dataCallback(CAMERA_MSG_PREVIEW_FRAME, mem);
1088        }
1089    } else {
1090        mLock.unlock();
1091    }
1092}
1093
1094// picture callback - postview image ready
1095void CameraService::Client::handlePostview(const sp<IMemory>& mem) {
1096    disableMsgType(CAMERA_MSG_POSTVIEW_FRAME);
1097
1098    sp<ICameraClient> c = mCameraClient;
1099    mLock.unlock();
1100    if (c != 0) {
1101        c->dataCallback(CAMERA_MSG_POSTVIEW_FRAME, mem);
1102    }
1103}
1104
1105// picture callback - raw image ready
1106void CameraService::Client::handleRawPicture(const sp<IMemory>& mem) {
1107    disableMsgType(CAMERA_MSG_RAW_IMAGE);
1108
1109    ssize_t offset;
1110    size_t size;
1111    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
1112
1113    sp<ICameraClient> c = mCameraClient;
1114    mLock.unlock();
1115    if (c != 0) {
1116        c->dataCallback(CAMERA_MSG_RAW_IMAGE, mem);
1117    }
1118}
1119
1120// picture callback - compressed picture ready
1121void CameraService::Client::handleCompressedPicture(const sp<IMemory>& mem) {
1122    disableMsgType(CAMERA_MSG_COMPRESSED_IMAGE);
1123
1124    sp<ICameraClient> c = mCameraClient;
1125    mLock.unlock();
1126    if (c != 0) {
1127        c->dataCallback(CAMERA_MSG_COMPRESSED_IMAGE, mem);
1128    }
1129}
1130
1131
1132void CameraService::Client::handleGenericNotify(int32_t msgType,
1133    int32_t ext1, int32_t ext2) {
1134    sp<ICameraClient> c = mCameraClient;
1135    mLock.unlock();
1136    if (c != 0) {
1137        c->notifyCallback(msgType, ext1, ext2);
1138    }
1139}
1140
1141void CameraService::Client::handleGenericData(int32_t msgType,
1142    const sp<IMemory>& dataPtr) {
1143    sp<ICameraClient> c = mCameraClient;
1144    mLock.unlock();
1145    if (c != 0) {
1146        c->dataCallback(msgType, dataPtr);
1147    }
1148}
1149
1150void CameraService::Client::handleGenericDataTimestamp(nsecs_t timestamp,
1151    int32_t msgType, const sp<IMemory>& dataPtr) {
1152    sp<ICameraClient> c = mCameraClient;
1153    mLock.unlock();
1154    if (c != 0) {
1155        c->dataCallbackTimestamp(timestamp, msgType, dataPtr);
1156    }
1157}
1158
1159void CameraService::Client::copyFrameAndPostCopiedFrame(
1160        const sp<ICameraClient>& client, const sp<IMemoryHeap>& heap,
1161        size_t offset, size_t size) {
1162    LOG2("copyFrameAndPostCopiedFrame");
1163    // It is necessary to copy out of pmem before sending this to
1164    // the callback. For efficiency, reuse the same MemoryHeapBase
1165    // provided it's big enough. Don't allocate the memory or
1166    // perform the copy if there's no callback.
1167    // hold the preview lock while we grab a reference to the preview buffer
1168    sp<MemoryHeapBase> previewBuffer;
1169
1170    if (mPreviewBuffer == 0) {
1171        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1172    } else if (size > mPreviewBuffer->virtualSize()) {
1173        mPreviewBuffer.clear();
1174        mPreviewBuffer = new MemoryHeapBase(size, 0, NULL);
1175    }
1176    if (mPreviewBuffer == 0) {
1177        LOGE("failed to allocate space for preview buffer");
1178        mLock.unlock();
1179        return;
1180    }
1181    previewBuffer = mPreviewBuffer;
1182
1183    memcpy(previewBuffer->base(), (uint8_t *)heap->base() + offset, size);
1184
1185    sp<MemoryBase> frame = new MemoryBase(previewBuffer, 0, size);
1186    if (frame == 0) {
1187        LOGE("failed to allocate space for frame callback");
1188        mLock.unlock();
1189        return;
1190    }
1191
1192    mLock.unlock();
1193    client->dataCallback(CAMERA_MSG_PREVIEW_FRAME, frame);
1194}
1195
1196// ----------------------------------------------------------------------------
1197
1198static const int kDumpLockRetries = 50;
1199static const int kDumpLockSleep = 60000;
1200
1201static bool tryLock(Mutex& mutex)
1202{
1203    bool locked = false;
1204    for (int i = 0; i < kDumpLockRetries; ++i) {
1205        if (mutex.tryLock() == NO_ERROR) {
1206            locked = true;
1207            break;
1208        }
1209        usleep(kDumpLockSleep);
1210    }
1211    return locked;
1212}
1213
1214status_t CameraService::dump(int fd, const Vector<String16>& args) {
1215    static const char* kDeadlockedString = "CameraService may be deadlocked\n";
1216
1217    const size_t SIZE = 256;
1218    char buffer[SIZE];
1219    String8 result;
1220    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1221        snprintf(buffer, SIZE, "Permission Denial: "
1222                "can't dump CameraService from pid=%d, uid=%d\n",
1223                getCallingPid(),
1224                getCallingUid());
1225        result.append(buffer);
1226        write(fd, result.string(), result.size());
1227    } else {
1228        bool locked = tryLock(mServiceLock);
1229        // failed to lock - CameraService is probably deadlocked
1230        if (!locked) {
1231            String8 result(kDeadlockedString);
1232            write(fd, result.string(), result.size());
1233        }
1234
1235        bool hasClient = false;
1236        for (int i = 0; i < mNumberOfCameras; i++) {
1237            sp<Client> client = mClient[i].promote();
1238            if (client == 0) continue;
1239            hasClient = true;
1240            sprintf(buffer, "Client[%d] (%p) PID: %d\n",
1241                    i,
1242                    client->getCameraClient()->asBinder().get(),
1243                    client->mClientPid);
1244            result.append(buffer);
1245            write(fd, result.string(), result.size());
1246            client->mHardware->dump(fd, args);
1247        }
1248        if (!hasClient) {
1249            result.append("No camera client yet.\n");
1250            write(fd, result.string(), result.size());
1251        }
1252
1253        if (locked) mServiceLock.unlock();
1254
1255        // change logging level
1256        int n = args.size();
1257        for (int i = 0; i + 1 < n; i++) {
1258            if (args[i] == String16("-v")) {
1259                String8 levelStr(args[i+1]);
1260                int level = atoi(levelStr.string());
1261                sprintf(buffer, "Set Log Level to %d", level);
1262                result.append(buffer);
1263                setLogLevel(level);
1264            }
1265        }
1266    }
1267    return NO_ERROR;
1268}
1269
1270sp<ISurface> CameraService::getISurface(const sp<Surface>& surface) {
1271    if (surface != 0) {
1272        return surface->getISurface();
1273    } else {
1274        return sp<ISurface>(0);
1275    }
1276}
1277
1278}; // namespace android
1279