CameraService.cpp revision 1a2952aee048ca7b1765e2bc09ebe9aeddaeafa3
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/Surface.h>
32#include <hardware/hardware.h>
33#include <media/AudioSystem.h>
34#include <media/mediaplayer.h>
35#include <utils/Errors.h>
36#include <utils/Log.h>
37#include <utils/String16.h>
38
39#include "CameraService.h"
40#include "CameraClient.h"
41#include "Camera2Client.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.
48volatile int32_t gLogLevel = 0;
49
50#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
51#define LOG2(...) ALOGD_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    ALOGI("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        ALOGE("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            ALOGE("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            ALOGE("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
137    LOG1("CameraService::connect E (pid %d, id %d)", callingPid, cameraId);
138
139    if (!mModule) {
140        ALOGE("Camera HAL module not loaded");
141        return NULL;
142    }
143
144    sp<Client> client;
145    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
146        ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
147            callingPid, cameraId);
148        return NULL;
149    }
150
151    char value[PROPERTY_VALUE_MAX];
152    property_get("sys.secpolicy.camera.disabled", value, "0");
153    if (strcmp(value, "1") == 0) {
154        // Camera is disabled by DevicePolicyManager.
155        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
156        return NULL;
157    }
158
159    Mutex::Autolock lock(mServiceLock);
160    if (mClient[cameraId] != 0) {
161        client = mClient[cameraId].promote();
162        if (client != 0) {
163            if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
164                LOG1("CameraService::connect X (pid %d) (the same client)",
165                     callingPid);
166                return client;
167            } else {
168                ALOGW("CameraService::connect X (pid %d) rejected (existing client).",
169                      callingPid);
170                return NULL;
171            }
172        }
173        mClient[cameraId].clear();
174    }
175
176    if (mBusy[cameraId]) {
177        ALOGW("CameraService::connect X (pid %d) rejected"
178                " (camera %d is still busy).", callingPid, cameraId);
179        return NULL;
180    }
181
182    struct camera_info info;
183    if (mModule->get_camera_info(cameraId, &info) != OK) {
184        ALOGE("Invalid camera id %d", cameraId);
185        return NULL;
186    }
187
188    int deviceVersion;
189    if (mModule->common.module_api_version == CAMERA_MODULE_API_VERSION_2_0) {
190        deviceVersion = info.device_version;
191    } else {
192        deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
193    }
194
195    switch(deviceVersion) {
196      case CAMERA_DEVICE_API_VERSION_1_0:
197        client = new CameraClient(this, cameraClient, cameraId,
198                info.facing, callingPid, getpid());
199        break;
200      case CAMERA_DEVICE_API_VERSION_2_0:
201        client = new Camera2Client(this, cameraClient, cameraId,
202                info.facing, callingPid, getpid());
203        break;
204      default:
205        ALOGE("Unknown camera device HAL version: %d", deviceVersion);
206        return NULL;
207    }
208
209    if (client->initialize(mModule) != OK) {
210        return NULL;
211    }
212
213    cameraClient->asBinder()->linkToDeath(this);
214
215    mClient[cameraId] = client;
216    LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, getpid());
217    return client;
218}
219
220void CameraService::removeClient(const sp<ICameraClient>& cameraClient) {
221    int callingPid = getCallingPid();
222    LOG1("CameraService::removeClient E (pid %d)", callingPid);
223
224    // Declare this before the lock to make absolutely sure the
225    // destructor won't be called with the lock held.
226    Mutex::Autolock lock(mServiceLock);
227
228    int outIndex;
229    sp<Client> client = findClientUnsafe(cameraClient->asBinder(), outIndex);
230
231    if (client != 0) {
232        // Found our camera, clear and leave.
233        LOG1("removeClient: clear camera %d", outIndex);
234        mClient[outIndex].clear();
235
236        client->unlinkToDeath(this);
237    }
238
239    LOG1("CameraService::removeClient X (pid %d)", callingPid);
240}
241
242sp<CameraService::Client> CameraService::findClientUnsafe(
243                        const wp<IBinder>& cameraClient, int& outIndex) {
244    sp<Client> client;
245
246    for (int i = 0; i < mNumberOfCameras; i++) {
247
248        // This happens when we have already disconnected (or this is
249        // just another unused camera).
250        if (mClient[i] == 0) continue;
251
252        // Promote mClient. It can fail if we are called from this path:
253        // Client::~Client() -> disconnect() -> removeClient().
254        client = mClient[i].promote();
255
256        // Clean up stale client entry
257        if (client == NULL) {
258            mClient[i].clear();
259            continue;
260        }
261
262        if (cameraClient == client->getCameraClient()->asBinder()) {
263            // Found our camera
264            outIndex = i;
265            return client;
266        }
267    }
268
269    outIndex = -1;
270    return NULL;
271}
272
273CameraService::Client* CameraService::getClientByIdUnsafe(int cameraId) {
274    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
275    return mClient[cameraId].unsafe_get();
276}
277
278Mutex* CameraService::getClientLockById(int cameraId) {
279    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
280    return &mClientLock[cameraId];
281}
282
283sp<CameraService::Client> CameraService::getClientByRemote(
284                                const wp<IBinder>& cameraClient) {
285
286    // Declare this before the lock to make absolutely sure the
287    // destructor won't be called with the lock held.
288    sp<Client> client;
289
290    Mutex::Autolock lock(mServiceLock);
291
292    int outIndex;
293    client = findClientUnsafe(cameraClient, outIndex);
294
295    return client;
296}
297
298status_t CameraService::onTransact(
299    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
300    // Permission checks
301    switch (code) {
302        case BnCameraService::CONNECT:
303            const int pid = getCallingPid();
304            const int self_pid = getpid();
305            if (pid != self_pid) {
306                // we're called from a different process, do the real check
307                if (!checkCallingPermission(
308                        String16("android.permission.CAMERA"))) {
309                    const int uid = getCallingUid();
310                    ALOGE("Permission Denial: "
311                         "can't use the camera pid=%d, uid=%d", pid, uid);
312                    return PERMISSION_DENIED;
313                }
314            }
315            break;
316    }
317
318    return BnCameraService::onTransact(code, data, reply, flags);
319}
320
321// The reason we need this busy bit is a new CameraService::connect() request
322// may come in while the previous Client's destructor has not been run or is
323// still running. If the last strong reference of the previous Client is gone
324// but the destructor has not been finished, we should not allow the new Client
325// to be created because we need to wait for the previous Client to tear down
326// the hardware first.
327void CameraService::setCameraBusy(int cameraId) {
328    android_atomic_write(1, &mBusy[cameraId]);
329
330    ALOGV("setCameraBusy cameraId=%d", cameraId);
331}
332
333void CameraService::setCameraFree(int cameraId) {
334    android_atomic_write(0, &mBusy[cameraId]);
335
336    ALOGV("setCameraFree cameraId=%d", cameraId);
337}
338
339// We share the media players for shutter and recording sound for all clients.
340// A reference count is kept to determine when we will actually release the
341// media players.
342
343MediaPlayer* CameraService::newMediaPlayer(const char *file) {
344    MediaPlayer* mp = new MediaPlayer();
345    if (mp->setDataSource(file, NULL) == NO_ERROR) {
346        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
347        mp->prepare();
348    } else {
349        ALOGE("Failed to load CameraService sounds: %s", file);
350        return NULL;
351    }
352    return mp;
353}
354
355void CameraService::loadSound() {
356    Mutex::Autolock lock(mSoundLock);
357    LOG1("CameraService::loadSound ref=%d", mSoundRef);
358    if (mSoundRef++) return;
359
360    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
361    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
362}
363
364void CameraService::releaseSound() {
365    Mutex::Autolock lock(mSoundLock);
366    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
367    if (--mSoundRef) return;
368
369    for (int i = 0; i < NUM_SOUNDS; i++) {
370        if (mSoundPlayer[i] != 0) {
371            mSoundPlayer[i]->disconnect();
372            mSoundPlayer[i].clear();
373        }
374    }
375}
376
377void CameraService::playSound(sound_kind kind) {
378    LOG1("playSound(%d)", kind);
379    Mutex::Autolock lock(mSoundLock);
380    sp<MediaPlayer> player = mSoundPlayer[kind];
381    if (player != 0) {
382        player->seekTo(0);
383        player->start();
384    }
385}
386
387// ----------------------------------------------------------------------------
388
389CameraService::Client::Client(const sp<CameraService>& cameraService,
390        const sp<ICameraClient>& cameraClient,
391        int cameraId, int cameraFacing, int clientPid, int servicePid) {
392    int callingPid = getCallingPid();
393    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
394
395    mCameraService = cameraService;
396    mCameraClient = cameraClient;
397    mCameraId = cameraId;
398    mCameraFacing = cameraFacing;
399    mClientPid = clientPid;
400    mServicePid = servicePid;
401    mDestructionStarted = false;
402
403    cameraService->setCameraBusy(cameraId);
404    cameraService->loadSound();
405    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
406}
407
408// tear down the client
409CameraService::Client::~Client() {
410    mCameraService->releaseSound();
411
412    // unconditionally disconnect. function is idempotent
413    Client::disconnect();
414}
415
416// ----------------------------------------------------------------------------
417
418Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
419    return gCameraService->getClientLockById((int) user);
420}
421
422// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
423// be acquired for this to be safe
424CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
425    Client* client = gCameraService->getClientByIdUnsafe((int) user);
426
427    // This could happen if the Client is in the process of shutting down (the
428    // last strong reference is gone, but the destructor hasn't finished
429    // stopping the hardware).
430    if (client == NULL) return NULL;
431
432    // destruction already started, so should not be accessed
433    if (client->mDestructionStarted) return NULL;
434
435    return client;
436}
437
438// NOTE: function is idempotent
439void CameraService::Client::disconnect() {
440    mCameraService->removeClient(mCameraClient);
441    mCameraService->setCameraFree(mCameraId);
442}
443
444// ----------------------------------------------------------------------------
445
446static const int kDumpLockRetries = 50;
447static const int kDumpLockSleep = 60000;
448
449static bool tryLock(Mutex& mutex)
450{
451    bool locked = false;
452    for (int i = 0; i < kDumpLockRetries; ++i) {
453        if (mutex.tryLock() == NO_ERROR) {
454            locked = true;
455            break;
456        }
457        usleep(kDumpLockSleep);
458    }
459    return locked;
460}
461
462status_t CameraService::dump(int fd, const Vector<String16>& args) {
463    String8 result;
464    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
465        result.appendFormat("Permission Denial: "
466                "can't dump CameraService from pid=%d, uid=%d\n",
467                getCallingPid(),
468                getCallingUid());
469        write(fd, result.string(), result.size());
470    } else {
471        bool locked = tryLock(mServiceLock);
472        // failed to lock - CameraService is probably deadlocked
473        if (!locked) {
474            result.append("CameraService may be deadlocked\n");
475            write(fd, result.string(), result.size());
476        }
477
478        bool hasClient = false;
479        if (!mModule) {
480            result = String8::format("No camera module available!\n");
481            write(fd, result.string(), result.size());
482            return NO_ERROR;
483        }
484
485        result = String8::format("Camera module HAL API version: 0x%x\n",
486                mModule->common.hal_api_version);
487        result.appendFormat("Camera module API version: 0x%x\n",
488                mModule->common.module_api_version);
489        result.appendFormat("Camera module name: %s\n",
490                mModule->common.name);
491        result.appendFormat("Camera module author: %s\n",
492                mModule->common.author);
493        result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
494        write(fd, result.string(), result.size());
495        for (int i = 0; i < mNumberOfCameras; i++) {
496            result = String8::format("Camera %d static information:\n", i);
497            camera_info info;
498
499            status_t rc = mModule->get_camera_info(i, &info);
500            if (rc != OK) {
501                result.appendFormat("  Error reading static information!\n");
502                write(fd, result.string(), result.size());
503            } else {
504                result.appendFormat("  Facing: %s\n",
505                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
506                result.appendFormat("  Orientation: %d\n", info.orientation);
507                int deviceVersion;
508                if (mModule->common.module_api_version <
509                        CAMERA_MODULE_API_VERSION_2_0) {
510                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
511                } else {
512                    deviceVersion = info.device_version;
513                }
514                result.appendFormat("  Device version: 0x%x\n", deviceVersion);
515                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
516                    result.appendFormat("  Device static metadata:\n");
517                    write(fd, result.string(), result.size());
518                    dump_indented_camera_metadata(info.static_camera_characteristics,
519                            fd, 2, 4);
520                } else {
521                    write(fd, result.string(), result.size());
522                }
523            }
524
525            sp<Client> client = mClient[i].promote();
526            if (client == 0) {
527                result = String8::format("  Device is closed, no client instance\n");
528                write(fd, result.string(), result.size());
529                continue;
530            }
531            hasClient = true;
532            result = String8::format("  Device is open. Client instance dump:\n");
533            write(fd, result.string(), result.size());
534            client->dump(fd, args);
535        }
536        if (!hasClient) {
537            result = String8::format("\nNo active camera clients yet.\n");
538            write(fd, result.string(), result.size());
539        }
540
541        if (locked) mServiceLock.unlock();
542
543        // change logging level
544        int n = args.size();
545        for (int i = 0; i + 1 < n; i++) {
546            String16 verboseOption("-v");
547            if (args[i] == verboseOption) {
548                String8 levelStr(args[i+1]);
549                int level = atoi(levelStr.string());
550                result = String8::format("\nSetting log level to %d.\n", level);
551                setLogLevel(level);
552                write(fd, result.string(), result.size());
553            }
554        }
555
556    }
557    return NO_ERROR;
558}
559
560/*virtual*/void CameraService::binderDied(
561    const wp<IBinder> &who) {
562
563    /**
564      * While tempting to promote the wp<IBinder> into a sp,
565      * it's actually not supported by the binder driver
566      */
567
568    ALOGV("java clients' binder died");
569
570    sp<Client> cameraClient = getClientByRemote(who);
571
572    if (cameraClient == 0) {
573        ALOGV("java clients' binder death already cleaned up (normal case)");
574        return;
575    }
576
577    ALOGW("Disconnecting camera client %p since the binder for it "
578          "died (this pid %d)", cameraClient.get(), getCallingPid());
579
580    cameraClient->disconnect();
581
582}
583
584}; // namespace android
585