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