CameraService.cpp revision ceb388d6c03c38b96dc41c0ea4804b749aa077c4
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/AppOpsManager.h>
26#include <binder/IPCThreadState.h>
27#include <binder/IServiceManager.h>
28#include <binder/MemoryBase.h>
29#include <binder/MemoryHeapBase.h>
30#include <cutils/atomic.h>
31#include <cutils/properties.h>
32#include <gui/Surface.h>
33#include <hardware/hardware.h>
34#include <media/AudioSystem.h>
35#include <media/mediaplayer.h>
36#include <utils/Errors.h>
37#include <utils/Log.h>
38#include <utils/String16.h>
39
40#include "CameraService.h"
41#include "CameraClient.h"
42#include "Camera2Client.h"
43#include "ProCamera2Client.h"
44
45namespace android {
46
47// ----------------------------------------------------------------------------
48// Logging support -- this is for debugging only
49// Use "adb shell dumpsys media.camera -v 1" to change it.
50volatile int32_t gLogLevel = 0;
51
52#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
53#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
54
55static void setLogLevel(int level) {
56    android_atomic_write(level, &gLogLevel);
57}
58
59// ----------------------------------------------------------------------------
60
61static int getCallingPid() {
62    return IPCThreadState::self()->getCallingPid();
63}
64
65static int getCallingUid() {
66    return IPCThreadState::self()->getCallingUid();
67}
68
69// ----------------------------------------------------------------------------
70
71// This is ugly and only safe if we never re-create the CameraService, but
72// should be ok for now.
73static CameraService *gCameraService;
74
75CameraService::CameraService()
76    :mSoundRef(0), mModule(0)
77{
78    ALOGI("CameraService started (pid=%d)", getpid());
79    gCameraService = this;
80}
81
82void CameraService::onFirstRef()
83{
84    LOG1("CameraService::onFirstRef");
85
86    BnCameraService::onFirstRef();
87
88    if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
89                (const hw_module_t **)&mModule) < 0) {
90        ALOGE("Could not load camera HAL module");
91        mNumberOfCameras = 0;
92    }
93    else {
94        ALOGI("Loaded \"%s\" camera module", mModule->common.name);
95        mNumberOfCameras = mModule->get_number_of_cameras();
96        if (mNumberOfCameras > MAX_CAMERAS) {
97            ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
98                    mNumberOfCameras, MAX_CAMERAS);
99            mNumberOfCameras = MAX_CAMERAS;
100        }
101        for (int i = 0; i < mNumberOfCameras; i++) {
102            setCameraFree(i);
103        }
104    }
105}
106
107CameraService::~CameraService() {
108    for (int i = 0; i < mNumberOfCameras; i++) {
109        if (mBusy[i]) {
110            ALOGE("camera %d is still in use in destructor!", i);
111        }
112    }
113
114    gCameraService = NULL;
115}
116
117int32_t CameraService::getNumberOfCameras() {
118    return mNumberOfCameras;
119}
120
121status_t CameraService::getCameraInfo(int cameraId,
122                                      struct CameraInfo* cameraInfo) {
123    if (!mModule) {
124        return NO_INIT;
125    }
126
127    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
128        return BAD_VALUE;
129    }
130
131    struct camera_info info;
132    status_t rc = mModule->get_camera_info(cameraId, &info);
133    cameraInfo->facing = info.facing;
134    cameraInfo->orientation = info.orientation;
135    return rc;
136}
137
138int CameraService::getDeviceVersion(int cameraId, int* facing) {
139    struct camera_info info;
140    if (mModule->get_camera_info(cameraId, &info) != OK) {
141        return -1;
142    }
143
144    int deviceVersion;
145    if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_0) {
146        deviceVersion = info.device_version;
147    } else {
148        deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
149    }
150
151    if (facing) {
152        *facing = info.facing;
153    }
154
155    return deviceVersion;
156}
157
158sp<ICamera> CameraService::connect(
159        const sp<ICameraClient>& cameraClient,
160        int cameraId,
161        const String16& clientPackageName,
162        int clientUid) {
163
164    String8 clientName8(clientPackageName);
165    int callingPid = getCallingPid();
166
167    LOG1("CameraService::connect E (pid %d \"%s\", id %d)", callingPid,
168            clientName8.string(), cameraId);
169
170    if (clientUid == USE_CALLING_UID) {
171        clientUid = getCallingUid();
172    } else {
173        // We only trust our own process to forward client UIDs
174        if (callingPid != getpid()) {
175            ALOGE("CameraService::connect X (pid %d) rejected (don't trust clientUid)",
176                    callingPid);
177            return NULL;
178        }
179    }
180
181    if (!mModule) {
182        ALOGE("Camera HAL module not loaded");
183        return NULL;
184    }
185
186    sp<Client> client;
187    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
188        ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
189            callingPid, cameraId);
190        return NULL;
191    }
192
193    char value[PROPERTY_VALUE_MAX];
194    property_get("sys.secpolicy.camera.disabled", value, "0");
195    if (strcmp(value, "1") == 0) {
196        // Camera is disabled by DevicePolicyManager.
197        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
198        return NULL;
199    }
200
201    Mutex::Autolock lock(mServiceLock);
202    if (mClient[cameraId] != 0) {
203        client = mClient[cameraId].promote();
204        if (client != 0) {
205            if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
206                LOG1("CameraService::connect X (pid %d) (the same client)",
207                     callingPid);
208                return client;
209            } else {
210                // TODOSC: need to support 1 regular client, multiple shared clients here
211                ALOGW("CameraService::connect X (pid %d) rejected (existing client).",
212                      callingPid);
213                return NULL;
214            }
215        }
216        mClient[cameraId].clear();
217    }
218
219    /*
220    mBusy is set to false as the last step of the Client destructor,
221    after which it is guaranteed that the Client destructor has finished (
222    including any inherited destructors)
223
224    We only need this for a Client subclasses since we don't allow
225    multiple Clents to be opened concurrently, but multiple BasicClient
226    would be fine
227    */
228    if (mBusy[cameraId]) {
229
230        ALOGW("CameraService::connect X (pid %d, \"%s\") rejected"
231                " (camera %d is still busy).", callingPid,
232                clientName8.string(), cameraId);
233        return NULL;
234    }
235
236    int facing = -1;
237    int deviceVersion = getDeviceVersion(cameraId, &facing);
238
239    switch(deviceVersion) {
240      case CAMERA_DEVICE_API_VERSION_1_0:
241        client = new CameraClient(this, cameraClient,
242                clientPackageName, cameraId,
243                facing, callingPid, clientUid, getpid());
244        break;
245      case CAMERA_DEVICE_API_VERSION_2_0:
246      case CAMERA_DEVICE_API_VERSION_2_1:
247        client = new Camera2Client(this, cameraClient,
248                clientPackageName, cameraId,
249                facing, callingPid, clientUid, getpid());
250        break;
251      case -1:
252        ALOGE("Invalid camera id %d", cameraId);
253        return NULL;
254      default:
255        ALOGE("Unknown camera device HAL version: %d", deviceVersion);
256        return NULL;
257    }
258
259    if (client->initialize(mModule) != OK) {
260        return NULL;
261    }
262
263    cameraClient->asBinder()->linkToDeath(this);
264
265    mClient[cameraId] = client;
266    LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, getpid());
267    return client;
268}
269
270sp<IProCameraUser> CameraService::connect(
271                                        const sp<IProCameraCallbacks>& cameraCb,
272                                        int cameraId)
273{
274    int callingPid = getCallingPid();
275
276    LOG1("CameraService::connectPro E (pid %d, id %d)", callingPid, cameraId);
277
278    if (!mModule) {
279        ALOGE("Camera HAL module not loaded");
280        return NULL;
281    }
282
283    sp<ProClient> client;
284    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
285        ALOGE("CameraService::connectPro X (pid %d) rejected (invalid cameraId %d).",
286            callingPid, cameraId);
287        return NULL;
288    }
289
290    char value[PROPERTY_VALUE_MAX];
291    property_get("sys.secpolicy.camera.disabled", value, "0");
292    if (strcmp(value, "1") == 0) {
293        // Camera is disabled by DevicePolicyManager.
294        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
295        return NULL;
296    }
297
298    int facing = -1;
299    int deviceVersion = getDeviceVersion(cameraId, &facing);
300
301    switch(deviceVersion) {
302      case CAMERA_DEVICE_API_VERSION_1_0:
303        ALOGE("Camera id %d uses HALv1, doesn't support ProCamera", cameraId);
304        return NULL;
305        break;
306      case CAMERA_DEVICE_API_VERSION_2_0:
307      case CAMERA_DEVICE_API_VERSION_2_1:
308        client = new ProCamera2Client(this, cameraCb, String16(),
309                cameraId, facing, callingPid, USE_CALLING_UID, getpid());
310        break;
311      case -1:
312        ALOGE("Invalid camera id %d", cameraId);
313        return NULL;
314      default:
315        ALOGE("Unknown camera device HAL version: %d", deviceVersion);
316        return NULL;
317    }
318
319    if (client->initialize(mModule) != OK) {
320        return NULL;
321    }
322
323    mProClientList[cameraId].push(client);
324
325    cameraCb->asBinder()->linkToDeath(this);
326
327    LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId,
328            getpid());
329    return client;
330
331
332    return NULL;
333}
334
335void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) {
336    int callingPid = getCallingPid();
337    LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid);
338
339    // Declare this before the lock to make absolutely sure the
340    // destructor won't be called with the lock held.
341    Mutex::Autolock lock(mServiceLock);
342
343    int outIndex;
344    sp<Client> client = findClientUnsafe(remoteBinder, outIndex);
345
346    if (client != 0) {
347        // Found our camera, clear and leave.
348        LOG1("removeClient: clear camera %d", outIndex);
349        mClient[outIndex].clear();
350
351        client->unlinkToDeath(this);
352    } else {
353
354        sp<ProClient> clientPro = findProClientUnsafe(remoteBinder);
355
356        if (clientPro != NULL) {
357            // Found our camera, clear and leave.
358            LOG1("removeClient: clear pro %p", clientPro.get());
359
360            clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this);
361        }
362    }
363
364    LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid);
365}
366
367sp<CameraService::ProClient> CameraService::findProClientUnsafe(
368                        const wp<IBinder>& cameraCallbacksRemote)
369{
370    sp<ProClient> clientPro;
371
372    for (int i = 0; i < mNumberOfCameras; ++i) {
373        Vector<size_t> removeIdx;
374
375        for (size_t j = 0; j < mProClientList[i].size(); ++j) {
376            wp<ProClient> cl = mProClientList[i][j];
377
378            sp<ProClient> clStrong = cl.promote();
379            if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) {
380                clientPro = clStrong;
381                break;
382            } else if (clStrong == NULL) {
383                // mark to clean up dead ptr
384                removeIdx.push(j);
385            }
386        }
387
388        // remove stale ptrs (in reverse so the indices dont change)
389        for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) {
390            mProClientList[i].removeAt(removeIdx[j]);
391        }
392
393    }
394
395    return clientPro;
396}
397
398sp<CameraService::Client> CameraService::findClientUnsafe(
399                        const wp<IBinder>& cameraClient, int& outIndex) {
400    sp<Client> client;
401
402    for (int i = 0; i < mNumberOfCameras; i++) {
403
404        // This happens when we have already disconnected (or this is
405        // just another unused camera).
406        if (mClient[i] == 0) continue;
407
408        // Promote mClient. It can fail if we are called from this path:
409        // Client::~Client() -> disconnect() -> removeClientByRemote().
410        client = mClient[i].promote();
411
412        // Clean up stale client entry
413        if (client == NULL) {
414            mClient[i].clear();
415            continue;
416        }
417
418        if (cameraClient == client->getCameraClient()->asBinder()) {
419            // Found our camera
420            outIndex = i;
421            return client;
422        }
423    }
424
425    outIndex = -1;
426    return NULL;
427}
428
429CameraService::Client* CameraService::getClientByIdUnsafe(int cameraId) {
430    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
431    return mClient[cameraId].unsafe_get();
432}
433
434Mutex* CameraService::getClientLockById(int cameraId) {
435    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
436    return &mClientLock[cameraId];
437}
438
439sp<CameraService::BasicClient> CameraService::getClientByRemote(
440                                const wp<IBinder>& cameraClient) {
441
442    // Declare this before the lock to make absolutely sure the
443    // destructor won't be called with the lock held.
444    sp<BasicClient> client;
445
446    Mutex::Autolock lock(mServiceLock);
447
448    int outIndex;
449    client = findClientUnsafe(cameraClient, outIndex);
450
451    return client;
452}
453
454status_t CameraService::onTransact(
455    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
456    // Permission checks
457    switch (code) {
458        case BnCameraService::CONNECT:
459        case BnCameraService::CONNECT_PRO:
460            const int pid = getCallingPid();
461            const int self_pid = getpid();
462            if (pid != self_pid) {
463                // we're called from a different process, do the real check
464                if (!checkCallingPermission(
465                        String16("android.permission.CAMERA"))) {
466                    const int uid = getCallingUid();
467                    ALOGE("Permission Denial: "
468                         "can't use the camera pid=%d, uid=%d", pid, uid);
469                    return PERMISSION_DENIED;
470                }
471            }
472            break;
473    }
474
475    return BnCameraService::onTransact(code, data, reply, flags);
476}
477
478// The reason we need this busy bit is a new CameraService::connect() request
479// may come in while the previous Client's destructor has not been run or is
480// still running. If the last strong reference of the previous Client is gone
481// but the destructor has not been finished, we should not allow the new Client
482// to be created because we need to wait for the previous Client to tear down
483// the hardware first.
484void CameraService::setCameraBusy(int cameraId) {
485    android_atomic_write(1, &mBusy[cameraId]);
486
487    ALOGV("setCameraBusy cameraId=%d", cameraId);
488}
489
490void CameraService::setCameraFree(int cameraId) {
491    android_atomic_write(0, &mBusy[cameraId]);
492
493    ALOGV("setCameraFree cameraId=%d", cameraId);
494}
495
496// We share the media players for shutter and recording sound for all clients.
497// A reference count is kept to determine when we will actually release the
498// media players.
499
500MediaPlayer* CameraService::newMediaPlayer(const char *file) {
501    MediaPlayer* mp = new MediaPlayer();
502    if (mp->setDataSource(file, NULL) == NO_ERROR) {
503        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
504        mp->prepare();
505    } else {
506        ALOGE("Failed to load CameraService sounds: %s", file);
507        return NULL;
508    }
509    return mp;
510}
511
512void CameraService::loadSound() {
513    Mutex::Autolock lock(mSoundLock);
514    LOG1("CameraService::loadSound ref=%d", mSoundRef);
515    if (mSoundRef++) return;
516
517    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
518    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
519}
520
521void CameraService::releaseSound() {
522    Mutex::Autolock lock(mSoundLock);
523    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
524    if (--mSoundRef) return;
525
526    for (int i = 0; i < NUM_SOUNDS; i++) {
527        if (mSoundPlayer[i] != 0) {
528            mSoundPlayer[i]->disconnect();
529            mSoundPlayer[i].clear();
530        }
531    }
532}
533
534void CameraService::playSound(sound_kind kind) {
535    LOG1("playSound(%d)", kind);
536    Mutex::Autolock lock(mSoundLock);
537    sp<MediaPlayer> player = mSoundPlayer[kind];
538    if (player != 0) {
539        player->seekTo(0);
540        player->start();
541    }
542}
543
544// ----------------------------------------------------------------------------
545
546CameraService::Client::Client(const sp<CameraService>& cameraService,
547        const sp<ICameraClient>& cameraClient,
548        const String16& clientPackageName,
549        int cameraId, int cameraFacing,
550        int clientPid, uid_t clientUid,
551        int servicePid) :
552        CameraService::BasicClient(cameraService, cameraClient->asBinder(),
553                clientPackageName,
554                cameraId, cameraFacing,
555                clientPid, clientUid,
556                servicePid)
557{
558    int callingPid = getCallingPid();
559    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
560
561    mCameraClient = cameraClient;
562
563    cameraService->setCameraBusy(cameraId);
564    cameraService->loadSound();
565
566    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
567}
568
569// tear down the client
570CameraService::Client::~Client() {
571    mDestructionStarted = true;
572
573    mCameraService->releaseSound();
574    finishCameraOps();
575    // unconditionally disconnect. function is idempotent
576    Client::disconnect();
577}
578
579CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
580        const sp<IBinder>& remoteCallback,
581        const String16& clientPackageName,
582        int cameraId, int cameraFacing,
583        int clientPid, uid_t clientUid,
584        int servicePid):
585        mClientPackageName(clientPackageName)
586{
587    mCameraService = cameraService;
588    mRemoteCallback = remoteCallback;
589    mCameraId = cameraId;
590    mCameraFacing = cameraFacing;
591    mClientPid = clientPid;
592    mClientUid = clientUid;
593    mServicePid = servicePid;
594    mOpsActive = false;
595    mDestructionStarted = false;
596}
597
598CameraService::BasicClient::~BasicClient() {
599    mDestructionStarted = true;
600}
601
602void CameraService::BasicClient::disconnect() {
603    mCameraService->removeClientByRemote(mRemoteCallback);
604}
605
606status_t CameraService::BasicClient::startCameraOps() {
607    int32_t res;
608
609    mOpsCallback = new OpsCallback(this);
610
611    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
612            mClientPackageName, mOpsCallback);
613    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
614            mClientUid, mClientPackageName);
615
616    if (res != AppOpsManager::MODE_ALLOWED) {
617        ALOGI("Camera %d: Access for \"%s\" has been revoked",
618                mCameraId, String8(mClientPackageName).string());
619        return PERMISSION_DENIED;
620    }
621    mOpsActive = true;
622    return OK;
623}
624
625status_t CameraService::BasicClient::finishCameraOps() {
626    if (mOpsActive) {
627        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
628                mClientPackageName);
629        mOpsActive = false;
630    }
631    mAppOpsManager.stopWatchingMode(mOpsCallback);
632    mOpsCallback.clear();
633
634    return OK;
635}
636
637void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
638    String8 name(packageName);
639    String8 myName(mClientPackageName);
640
641    if (op != AppOpsManager::OP_CAMERA) {
642        ALOGW("Unexpected app ops notification received: %d", op);
643        return;
644    }
645
646    int32_t res;
647    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
648            mClientUid, mClientPackageName);
649    ALOGV("checkOp returns: %d, %s ", res,
650            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
651            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
652            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
653            "UNKNOWN");
654
655    if (res != AppOpsManager::MODE_ALLOWED) {
656        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
657                myName.string());
658        // Reset the client PID to allow server-initiated disconnect,
659        // and to prevent further calls by client.
660        mClientPid = getCallingPid();
661        notifyError();
662        disconnect();
663    }
664}
665
666// ----------------------------------------------------------------------------
667
668Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
669    return gCameraService->getClientLockById((int) user);
670}
671
672// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
673// be acquired for this to be safe
674CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
675    Client* client = gCameraService->getClientByIdUnsafe((int) user);
676
677    // This could happen if the Client is in the process of shutting down (the
678    // last strong reference is gone, but the destructor hasn't finished
679    // stopping the hardware).
680    if (client == NULL) return NULL;
681
682    // destruction already started, so should not be accessed
683    if (client->mDestructionStarted) return NULL;
684
685    return client;
686}
687
688void CameraService::Client::notifyError() {
689    mCameraClient->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
690}
691
692// NOTE: function is idempotent
693void CameraService::Client::disconnect() {
694    BasicClient::disconnect();
695    mCameraService->setCameraFree(mCameraId);
696}
697
698CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
699        mClient(client) {
700}
701
702void CameraService::Client::OpsCallback::opChanged(int32_t op,
703        const String16& packageName) {
704    sp<BasicClient> client = mClient.promote();
705    if (client != NULL) {
706        client->opChanged(op, packageName);
707    }
708}
709
710// ----------------------------------------------------------------------------
711//                  IProCamera
712// ----------------------------------------------------------------------------
713
714CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
715        const sp<IProCameraCallbacks>& remoteCallback,
716        const String16& clientPackageName,
717        int cameraId,
718        int cameraFacing,
719        int clientPid,
720        uid_t clientUid,
721        int servicePid)
722        : CameraService::BasicClient(cameraService, remoteCallback->asBinder(),
723                clientPackageName, cameraId, cameraFacing,
724                clientPid,  clientUid, servicePid)
725{
726    mRemoteCallback = remoteCallback;
727}
728
729CameraService::ProClient::~ProClient() {
730    mDestructionStarted = true;
731
732    ProClient::disconnect();
733}
734
735status_t CameraService::ProClient::connect(const sp<IProCameraCallbacks>& callbacks) {
736    ALOGE("%s: not implemented yet", __FUNCTION__);
737
738    return INVALID_OPERATION;
739}
740
741void CameraService::ProClient::disconnect() {
742    BasicClient::disconnect();
743}
744
745status_t CameraService::ProClient::initialize(camera_module_t* module)
746{
747    ALOGW("%s: not implemented yet", __FUNCTION__);
748    return OK;
749}
750
751status_t CameraService::ProClient::exclusiveTryLock() {
752    ALOGE("%s: not implemented yet", __FUNCTION__);
753    return INVALID_OPERATION;
754}
755
756status_t CameraService::ProClient::exclusiveLock() {
757    ALOGE("%s: not implemented yet", __FUNCTION__);
758    return INVALID_OPERATION;
759}
760
761status_t CameraService::ProClient::exclusiveUnlock() {
762    ALOGE("%s: not implemented yet", __FUNCTION__);
763    return INVALID_OPERATION;
764}
765
766bool CameraService::ProClient::hasExclusiveLock() {
767    ALOGE("%s: not implemented yet", __FUNCTION__);
768    return false;
769}
770
771status_t CameraService::ProClient::submitRequest(camera_metadata_t* request, bool streaming) {
772    ALOGE("%s: not implemented yet", __FUNCTION__);
773
774    free_camera_metadata(request);
775
776    return INVALID_OPERATION;
777}
778
779status_t CameraService::ProClient::cancelRequest(int requestId) {
780    ALOGE("%s: not implemented yet", __FUNCTION__);
781
782    return INVALID_OPERATION;
783}
784
785status_t CameraService::ProClient::requestStream(int streamId) {
786    ALOGE("%s: not implemented yet", __FUNCTION__);
787
788    return INVALID_OPERATION;
789}
790
791status_t CameraService::ProClient::cancelStream(int streamId) {
792    ALOGE("%s: not implemented yet", __FUNCTION__);
793
794    return INVALID_OPERATION;
795}
796
797void CameraService::ProClient::notifyError() {
798    ALOGE("%s: not implemented yet", __FUNCTION__);
799}
800
801// ----------------------------------------------------------------------------
802
803static const int kDumpLockRetries = 50;
804static const int kDumpLockSleep = 60000;
805
806static bool tryLock(Mutex& mutex)
807{
808    bool locked = false;
809    for (int i = 0; i < kDumpLockRetries; ++i) {
810        if (mutex.tryLock() == NO_ERROR) {
811            locked = true;
812            break;
813        }
814        usleep(kDumpLockSleep);
815    }
816    return locked;
817}
818
819status_t CameraService::dump(int fd, const Vector<String16>& args) {
820    String8 result;
821    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
822        result.appendFormat("Permission Denial: "
823                "can't dump CameraService from pid=%d, uid=%d\n",
824                getCallingPid(),
825                getCallingUid());
826        write(fd, result.string(), result.size());
827    } else {
828        bool locked = tryLock(mServiceLock);
829        // failed to lock - CameraService is probably deadlocked
830        if (!locked) {
831            result.append("CameraService may be deadlocked\n");
832            write(fd, result.string(), result.size());
833        }
834
835        bool hasClient = false;
836        if (!mModule) {
837            result = String8::format("No camera module available!\n");
838            write(fd, result.string(), result.size());
839            return NO_ERROR;
840        }
841
842        result = String8::format("Camera module HAL API version: 0x%x\n",
843                mModule->common.hal_api_version);
844        result.appendFormat("Camera module API version: 0x%x\n",
845                mModule->common.module_api_version);
846        result.appendFormat("Camera module name: %s\n",
847                mModule->common.name);
848        result.appendFormat("Camera module author: %s\n",
849                mModule->common.author);
850        result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
851        write(fd, result.string(), result.size());
852        for (int i = 0; i < mNumberOfCameras; i++) {
853            result = String8::format("Camera %d static information:\n", i);
854            camera_info info;
855
856            status_t rc = mModule->get_camera_info(i, &info);
857            if (rc != OK) {
858                result.appendFormat("  Error reading static information!\n");
859                write(fd, result.string(), result.size());
860            } else {
861                result.appendFormat("  Facing: %s\n",
862                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
863                result.appendFormat("  Orientation: %d\n", info.orientation);
864                int deviceVersion;
865                if (mModule->common.module_api_version <
866                        CAMERA_MODULE_API_VERSION_2_0) {
867                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
868                } else {
869                    deviceVersion = info.device_version;
870                }
871                result.appendFormat("  Device version: 0x%x\n", deviceVersion);
872                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
873                    result.appendFormat("  Device static metadata:\n");
874                    write(fd, result.string(), result.size());
875                    dump_indented_camera_metadata(info.static_camera_characteristics,
876                            fd, 2, 4);
877                } else {
878                    write(fd, result.string(), result.size());
879                }
880            }
881
882            sp<Client> client = mClient[i].promote();
883            if (client == 0) {
884                result = String8::format("  Device is closed, no client instance\n");
885                write(fd, result.string(), result.size());
886                continue;
887            }
888            hasClient = true;
889            result = String8::format("  Device is open. Client instance dump:\n");
890            write(fd, result.string(), result.size());
891            client->dump(fd, args);
892        }
893        if (!hasClient) {
894            result = String8::format("\nNo active camera clients yet.\n");
895            write(fd, result.string(), result.size());
896        }
897
898        if (locked) mServiceLock.unlock();
899
900        // change logging level
901        int n = args.size();
902        for (int i = 0; i + 1 < n; i++) {
903            String16 verboseOption("-v");
904            if (args[i] == verboseOption) {
905                String8 levelStr(args[i+1]);
906                int level = atoi(levelStr.string());
907                result = String8::format("\nSetting log level to %d.\n", level);
908                setLogLevel(level);
909                write(fd, result.string(), result.size());
910            }
911        }
912
913    }
914    return NO_ERROR;
915}
916
917/*virtual*/void CameraService::binderDied(
918    const wp<IBinder> &who) {
919
920    /**
921      * While tempting to promote the wp<IBinder> into a sp,
922      * it's actually not supported by the binder driver
923      */
924
925    ALOGV("java clients' binder died");
926
927    sp<BasicClient> cameraClient = getClientByRemote(who);
928
929    if (cameraClient == 0) {
930        ALOGV("java clients' binder death already cleaned up (normal case)");
931        return;
932    }
933
934    ALOGW("Disconnecting camera client %p since the binder for it "
935          "died (this pid %d)", cameraClient.get(), getCallingPid());
936
937    cameraClient->disconnect();
938
939}
940
941}; // namespace android
942