CameraService.cpp revision b99c5b8eebb35133a08c46b015624bd4c4a6c477
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      case CAMERA_DEVICE_API_VERSION_3_0:
248        client = new Camera2Client(this, cameraClient,
249                clientPackageName, cameraId,
250                facing, callingPid, clientUid, getpid(),
251                deviceVersion);
252        break;
253      case -1:
254        ALOGE("Invalid camera id %d", cameraId);
255        return NULL;
256      default:
257        ALOGE("Unknown camera device HAL version: %d", deviceVersion);
258        return NULL;
259    }
260
261    if (client->initialize(mModule) != OK) {
262        return NULL;
263    }
264
265    cameraClient->asBinder()->linkToDeath(this);
266
267    mClient[cameraId] = client;
268    LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, getpid());
269    return client;
270}
271
272sp<IProCameraUser> CameraService::connect(
273                                        const sp<IProCameraCallbacks>& cameraCb,
274                                        int cameraId,
275                                        const String16& clientPackageName,
276                                        int clientUid)
277{
278    int callingPid = getCallingPid();
279
280    // TODO: use clientPackageName and clientUid with appOpsMangr
281
282    LOG1("CameraService::connectPro E (pid %d, id %d)", callingPid, cameraId);
283
284    if (!mModule) {
285        ALOGE("Camera HAL module not loaded");
286        return NULL;
287    }
288
289    sp<ProClient> client;
290    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
291        ALOGE("CameraService::connectPro X (pid %d) rejected (invalid cameraId %d).",
292            callingPid, cameraId);
293        return NULL;
294    }
295
296    char value[PROPERTY_VALUE_MAX];
297    property_get("sys.secpolicy.camera.disabled", value, "0");
298    if (strcmp(value, "1") == 0) {
299        // Camera is disabled by DevicePolicyManager.
300        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
301        return NULL;
302    }
303
304    int facing = -1;
305    int deviceVersion = getDeviceVersion(cameraId, &facing);
306
307    switch(deviceVersion) {
308      case CAMERA_DEVICE_API_VERSION_1_0:
309        ALOGE("Camera id %d uses HALv1, doesn't support ProCamera", cameraId);
310        return NULL;
311        break;
312      case CAMERA_DEVICE_API_VERSION_2_0:
313      case CAMERA_DEVICE_API_VERSION_2_1:
314        client = new ProCamera2Client(this, cameraCb, String16(),
315                cameraId, facing, callingPid, USE_CALLING_UID, getpid());
316        break;
317      case -1:
318        ALOGE("Invalid camera id %d", cameraId);
319        return NULL;
320      default:
321        ALOGE("Unknown camera device HAL version: %d", deviceVersion);
322        return NULL;
323    }
324
325    if (client->initialize(mModule) != OK) {
326        return NULL;
327    }
328
329    mProClientList[cameraId].push(client);
330
331    cameraCb->asBinder()->linkToDeath(this);
332
333    LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId,
334            getpid());
335    return client;
336
337
338    return NULL;
339}
340
341void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) {
342    int callingPid = getCallingPid();
343    LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid);
344
345    // Declare this before the lock to make absolutely sure the
346    // destructor won't be called with the lock held.
347    Mutex::Autolock lock(mServiceLock);
348
349    int outIndex;
350    sp<Client> client = findClientUnsafe(remoteBinder, outIndex);
351
352    if (client != 0) {
353        // Found our camera, clear and leave.
354        LOG1("removeClient: clear camera %d", outIndex);
355        mClient[outIndex].clear();
356
357        client->unlinkToDeath(this);
358    } else {
359
360        sp<ProClient> clientPro = findProClientUnsafe(remoteBinder);
361
362        if (clientPro != NULL) {
363            // Found our camera, clear and leave.
364            LOG1("removeClient: clear pro %p", clientPro.get());
365
366            clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this);
367        }
368    }
369
370    LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid);
371}
372
373sp<CameraService::ProClient> CameraService::findProClientUnsafe(
374                        const wp<IBinder>& cameraCallbacksRemote)
375{
376    sp<ProClient> clientPro;
377
378    for (int i = 0; i < mNumberOfCameras; ++i) {
379        Vector<size_t> removeIdx;
380
381        for (size_t j = 0; j < mProClientList[i].size(); ++j) {
382            wp<ProClient> cl = mProClientList[i][j];
383
384            sp<ProClient> clStrong = cl.promote();
385            if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) {
386                clientPro = clStrong;
387                break;
388            } else if (clStrong == NULL) {
389                // mark to clean up dead ptr
390                removeIdx.push(j);
391            }
392        }
393
394        // remove stale ptrs (in reverse so the indices dont change)
395        for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) {
396            mProClientList[i].removeAt(removeIdx[j]);
397        }
398
399    }
400
401    return clientPro;
402}
403
404sp<CameraService::Client> CameraService::findClientUnsafe(
405                        const wp<IBinder>& cameraClient, int& outIndex) {
406    sp<Client> client;
407
408    for (int i = 0; i < mNumberOfCameras; i++) {
409
410        // This happens when we have already disconnected (or this is
411        // just another unused camera).
412        if (mClient[i] == 0) continue;
413
414        // Promote mClient. It can fail if we are called from this path:
415        // Client::~Client() -> disconnect() -> removeClientByRemote().
416        client = mClient[i].promote();
417
418        // Clean up stale client entry
419        if (client == NULL) {
420            mClient[i].clear();
421            continue;
422        }
423
424        if (cameraClient == client->getCameraClient()->asBinder()) {
425            // Found our camera
426            outIndex = i;
427            return client;
428        }
429    }
430
431    outIndex = -1;
432    return NULL;
433}
434
435CameraService::Client* CameraService::getClientByIdUnsafe(int cameraId) {
436    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
437    return mClient[cameraId].unsafe_get();
438}
439
440Mutex* CameraService::getClientLockById(int cameraId) {
441    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
442    return &mClientLock[cameraId];
443}
444
445sp<CameraService::BasicClient> CameraService::getClientByRemote(
446                                const wp<IBinder>& cameraClient) {
447
448    // Declare this before the lock to make absolutely sure the
449    // destructor won't be called with the lock held.
450    sp<BasicClient> client;
451
452    Mutex::Autolock lock(mServiceLock);
453
454    int outIndex;
455    client = findClientUnsafe(cameraClient, outIndex);
456
457    return client;
458}
459
460status_t CameraService::onTransact(
461    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
462    // Permission checks
463    switch (code) {
464        case BnCameraService::CONNECT:
465        case BnCameraService::CONNECT_PRO:
466            const int pid = getCallingPid();
467            const int self_pid = getpid();
468            if (pid != self_pid) {
469                // we're called from a different process, do the real check
470                if (!checkCallingPermission(
471                        String16("android.permission.CAMERA"))) {
472                    const int uid = getCallingUid();
473                    ALOGE("Permission Denial: "
474                         "can't use the camera pid=%d, uid=%d", pid, uid);
475                    return PERMISSION_DENIED;
476                }
477            }
478            break;
479    }
480
481    return BnCameraService::onTransact(code, data, reply, flags);
482}
483
484// The reason we need this busy bit is a new CameraService::connect() request
485// may come in while the previous Client's destructor has not been run or is
486// still running. If the last strong reference of the previous Client is gone
487// but the destructor has not been finished, we should not allow the new Client
488// to be created because we need to wait for the previous Client to tear down
489// the hardware first.
490void CameraService::setCameraBusy(int cameraId) {
491    android_atomic_write(1, &mBusy[cameraId]);
492
493    ALOGV("setCameraBusy cameraId=%d", cameraId);
494}
495
496void CameraService::setCameraFree(int cameraId) {
497    android_atomic_write(0, &mBusy[cameraId]);
498
499    ALOGV("setCameraFree cameraId=%d", cameraId);
500}
501
502// We share the media players for shutter and recording sound for all clients.
503// A reference count is kept to determine when we will actually release the
504// media players.
505
506MediaPlayer* CameraService::newMediaPlayer(const char *file) {
507    MediaPlayer* mp = new MediaPlayer();
508    if (mp->setDataSource(file, NULL) == NO_ERROR) {
509        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
510        mp->prepare();
511    } else {
512        ALOGE("Failed to load CameraService sounds: %s", file);
513        return NULL;
514    }
515    return mp;
516}
517
518void CameraService::loadSound() {
519    Mutex::Autolock lock(mSoundLock);
520    LOG1("CameraService::loadSound ref=%d", mSoundRef);
521    if (mSoundRef++) return;
522
523    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
524    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
525}
526
527void CameraService::releaseSound() {
528    Mutex::Autolock lock(mSoundLock);
529    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
530    if (--mSoundRef) return;
531
532    for (int i = 0; i < NUM_SOUNDS; i++) {
533        if (mSoundPlayer[i] != 0) {
534            mSoundPlayer[i]->disconnect();
535            mSoundPlayer[i].clear();
536        }
537    }
538}
539
540void CameraService::playSound(sound_kind kind) {
541    LOG1("playSound(%d)", kind);
542    Mutex::Autolock lock(mSoundLock);
543    sp<MediaPlayer> player = mSoundPlayer[kind];
544    if (player != 0) {
545        player->seekTo(0);
546        player->start();
547    }
548}
549
550// ----------------------------------------------------------------------------
551
552CameraService::Client::Client(const sp<CameraService>& cameraService,
553        const sp<ICameraClient>& cameraClient,
554        const String16& clientPackageName,
555        int cameraId, int cameraFacing,
556        int clientPid, uid_t clientUid,
557        int servicePid) :
558        CameraService::BasicClient(cameraService, cameraClient->asBinder(),
559                clientPackageName,
560                cameraId, cameraFacing,
561                clientPid, clientUid,
562                servicePid)
563{
564    int callingPid = getCallingPid();
565    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
566
567    mCameraClient = cameraClient;
568
569    cameraService->setCameraBusy(cameraId);
570    cameraService->loadSound();
571
572    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
573}
574
575// tear down the client
576CameraService::Client::~Client() {
577    mDestructionStarted = true;
578
579    mCameraService->releaseSound();
580    finishCameraOps();
581    // unconditionally disconnect. function is idempotent
582    Client::disconnect();
583}
584
585CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
586        const sp<IBinder>& remoteCallback,
587        const String16& clientPackageName,
588        int cameraId, int cameraFacing,
589        int clientPid, uid_t clientUid,
590        int servicePid):
591        mClientPackageName(clientPackageName)
592{
593    mCameraService = cameraService;
594    mRemoteCallback = remoteCallback;
595    mCameraId = cameraId;
596    mCameraFacing = cameraFacing;
597    mClientPid = clientPid;
598    mClientUid = clientUid;
599    mServicePid = servicePid;
600    mOpsActive = false;
601    mDestructionStarted = false;
602}
603
604CameraService::BasicClient::~BasicClient() {
605    mDestructionStarted = true;
606}
607
608void CameraService::BasicClient::disconnect() {
609    mCameraService->removeClientByRemote(mRemoteCallback);
610}
611
612status_t CameraService::BasicClient::startCameraOps() {
613    int32_t res;
614
615    mOpsCallback = new OpsCallback(this);
616
617    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
618            mClientPackageName, mOpsCallback);
619    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
620            mClientUid, mClientPackageName);
621
622    if (res != AppOpsManager::MODE_ALLOWED) {
623        ALOGI("Camera %d: Access for \"%s\" has been revoked",
624                mCameraId, String8(mClientPackageName).string());
625        return PERMISSION_DENIED;
626    }
627    mOpsActive = true;
628    return OK;
629}
630
631status_t CameraService::BasicClient::finishCameraOps() {
632    if (mOpsActive) {
633        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
634                mClientPackageName);
635        mOpsActive = false;
636    }
637    mAppOpsManager.stopWatchingMode(mOpsCallback);
638    mOpsCallback.clear();
639
640    return OK;
641}
642
643void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
644    String8 name(packageName);
645    String8 myName(mClientPackageName);
646
647    if (op != AppOpsManager::OP_CAMERA) {
648        ALOGW("Unexpected app ops notification received: %d", op);
649        return;
650    }
651
652    int32_t res;
653    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
654            mClientUid, mClientPackageName);
655    ALOGV("checkOp returns: %d, %s ", res,
656            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
657            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
658            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
659            "UNKNOWN");
660
661    if (res != AppOpsManager::MODE_ALLOWED) {
662        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
663                myName.string());
664        // Reset the client PID to allow server-initiated disconnect,
665        // and to prevent further calls by client.
666        mClientPid = getCallingPid();
667        notifyError();
668        disconnect();
669    }
670}
671
672// ----------------------------------------------------------------------------
673
674Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
675    return gCameraService->getClientLockById((int) user);
676}
677
678// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
679// be acquired for this to be safe
680CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
681    Client* client = gCameraService->getClientByIdUnsafe((int) user);
682
683    // This could happen if the Client is in the process of shutting down (the
684    // last strong reference is gone, but the destructor hasn't finished
685    // stopping the hardware).
686    if (client == NULL) return NULL;
687
688    // destruction already started, so should not be accessed
689    if (client->mDestructionStarted) return NULL;
690
691    return client;
692}
693
694void CameraService::Client::notifyError() {
695    mCameraClient->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
696}
697
698// NOTE: function is idempotent
699void CameraService::Client::disconnect() {
700    BasicClient::disconnect();
701    mCameraService->setCameraFree(mCameraId);
702}
703
704CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
705        mClient(client) {
706}
707
708void CameraService::Client::OpsCallback::opChanged(int32_t op,
709        const String16& packageName) {
710    sp<BasicClient> client = mClient.promote();
711    if (client != NULL) {
712        client->opChanged(op, packageName);
713    }
714}
715
716// ----------------------------------------------------------------------------
717//                  IProCamera
718// ----------------------------------------------------------------------------
719
720CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
721        const sp<IProCameraCallbacks>& remoteCallback,
722        const String16& clientPackageName,
723        int cameraId,
724        int cameraFacing,
725        int clientPid,
726        uid_t clientUid,
727        int servicePid)
728        : CameraService::BasicClient(cameraService, remoteCallback->asBinder(),
729                clientPackageName, cameraId, cameraFacing,
730                clientPid,  clientUid, servicePid)
731{
732    mRemoteCallback = remoteCallback;
733}
734
735CameraService::ProClient::~ProClient() {
736    mDestructionStarted = true;
737
738    ProClient::disconnect();
739}
740
741status_t CameraService::ProClient::connect(const sp<IProCameraCallbacks>& callbacks) {
742    ALOGE("%s: not implemented yet", __FUNCTION__);
743
744    return INVALID_OPERATION;
745}
746
747void CameraService::ProClient::disconnect() {
748    BasicClient::disconnect();
749}
750
751status_t CameraService::ProClient::initialize(camera_module_t* module)
752{
753    ALOGW("%s: not implemented yet", __FUNCTION__);
754    return OK;
755}
756
757status_t CameraService::ProClient::exclusiveTryLock() {
758    ALOGE("%s: not implemented yet", __FUNCTION__);
759    return INVALID_OPERATION;
760}
761
762status_t CameraService::ProClient::exclusiveLock() {
763    ALOGE("%s: not implemented yet", __FUNCTION__);
764    return INVALID_OPERATION;
765}
766
767status_t CameraService::ProClient::exclusiveUnlock() {
768    ALOGE("%s: not implemented yet", __FUNCTION__);
769    return INVALID_OPERATION;
770}
771
772bool CameraService::ProClient::hasExclusiveLock() {
773    ALOGE("%s: not implemented yet", __FUNCTION__);
774    return false;
775}
776
777status_t CameraService::ProClient::submitRequest(camera_metadata_t* request, bool streaming) {
778    ALOGE("%s: not implemented yet", __FUNCTION__);
779
780    free_camera_metadata(request);
781
782    return INVALID_OPERATION;
783}
784
785status_t CameraService::ProClient::cancelRequest(int requestId) {
786    ALOGE("%s: not implemented yet", __FUNCTION__);
787
788    return INVALID_OPERATION;
789}
790
791status_t CameraService::ProClient::requestStream(int streamId) {
792    ALOGE("%s: not implemented yet", __FUNCTION__);
793
794    return INVALID_OPERATION;
795}
796
797status_t CameraService::ProClient::cancelStream(int streamId) {
798    ALOGE("%s: not implemented yet", __FUNCTION__);
799
800    return INVALID_OPERATION;
801}
802
803void CameraService::ProClient::notifyError() {
804    ALOGE("%s: not implemented yet", __FUNCTION__);
805}
806
807// ----------------------------------------------------------------------------
808
809static const int kDumpLockRetries = 50;
810static const int kDumpLockSleep = 60000;
811
812static bool tryLock(Mutex& mutex)
813{
814    bool locked = false;
815    for (int i = 0; i < kDumpLockRetries; ++i) {
816        if (mutex.tryLock() == NO_ERROR) {
817            locked = true;
818            break;
819        }
820        usleep(kDumpLockSleep);
821    }
822    return locked;
823}
824
825status_t CameraService::dump(int fd, const Vector<String16>& args) {
826    String8 result;
827    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
828        result.appendFormat("Permission Denial: "
829                "can't dump CameraService from pid=%d, uid=%d\n",
830                getCallingPid(),
831                getCallingUid());
832        write(fd, result.string(), result.size());
833    } else {
834        bool locked = tryLock(mServiceLock);
835        // failed to lock - CameraService is probably deadlocked
836        if (!locked) {
837            result.append("CameraService may be deadlocked\n");
838            write(fd, result.string(), result.size());
839        }
840
841        bool hasClient = false;
842        if (!mModule) {
843            result = String8::format("No camera module available!\n");
844            write(fd, result.string(), result.size());
845            return NO_ERROR;
846        }
847
848        result = String8::format("Camera module HAL API version: 0x%x\n",
849                mModule->common.hal_api_version);
850        result.appendFormat("Camera module API version: 0x%x\n",
851                mModule->common.module_api_version);
852        result.appendFormat("Camera module name: %s\n",
853                mModule->common.name);
854        result.appendFormat("Camera module author: %s\n",
855                mModule->common.author);
856        result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
857        write(fd, result.string(), result.size());
858        for (int i = 0; i < mNumberOfCameras; i++) {
859            result = String8::format("Camera %d static information:\n", i);
860            camera_info info;
861
862            status_t rc = mModule->get_camera_info(i, &info);
863            if (rc != OK) {
864                result.appendFormat("  Error reading static information!\n");
865                write(fd, result.string(), result.size());
866            } else {
867                result.appendFormat("  Facing: %s\n",
868                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
869                result.appendFormat("  Orientation: %d\n", info.orientation);
870                int deviceVersion;
871                if (mModule->common.module_api_version <
872                        CAMERA_MODULE_API_VERSION_2_0) {
873                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
874                } else {
875                    deviceVersion = info.device_version;
876                }
877                result.appendFormat("  Device version: 0x%x\n", deviceVersion);
878                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
879                    result.appendFormat("  Device static metadata:\n");
880                    write(fd, result.string(), result.size());
881                    dump_indented_camera_metadata(info.static_camera_characteristics,
882                            fd, 2, 4);
883                } else {
884                    write(fd, result.string(), result.size());
885                }
886            }
887
888            sp<Client> client = mClient[i].promote();
889            if (client == 0) {
890                result = String8::format("  Device is closed, no client instance\n");
891                write(fd, result.string(), result.size());
892                continue;
893            }
894            hasClient = true;
895            result = String8::format("  Device is open. Client instance dump:\n");
896            write(fd, result.string(), result.size());
897            client->dump(fd, args);
898        }
899        if (!hasClient) {
900            result = String8::format("\nNo active camera clients yet.\n");
901            write(fd, result.string(), result.size());
902        }
903
904        if (locked) mServiceLock.unlock();
905
906        // change logging level
907        int n = args.size();
908        for (int i = 0; i + 1 < n; i++) {
909            String16 verboseOption("-v");
910            if (args[i] == verboseOption) {
911                String8 levelStr(args[i+1]);
912                int level = atoi(levelStr.string());
913                result = String8::format("\nSetting log level to %d.\n", level);
914                setLogLevel(level);
915                write(fd, result.string(), result.size());
916            }
917        }
918
919    }
920    return NO_ERROR;
921}
922
923/*virtual*/void CameraService::binderDied(
924    const wp<IBinder> &who) {
925
926    /**
927      * While tempting to promote the wp<IBinder> into a sp,
928      * it's actually not supported by the binder driver
929      */
930
931    ALOGV("java clients' binder died");
932
933    sp<BasicClient> cameraClient = getClientByRemote(who);
934
935    if (cameraClient == 0) {
936        ALOGV("java clients' binder death already cleaned up (normal case)");
937        return;
938    }
939
940    ALOGW("Disconnecting camera client %p since the binder for it "
941          "died (this pid %d)", cameraClient.get(), getCallingPid());
942
943    cameraClient->disconnect();
944
945}
946
947}; // namespace android
948