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