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