CameraService.cpp revision 1b86fe063badb5f28c467ade39be0f4008688947
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/IMediaHTTPService.h>
36#include <media/mediaplayer.h>
37#include <utils/Errors.h>
38#include <utils/Log.h>
39#include <utils/String16.h>
40
41#include "CameraService.h"
42#include "api1/CameraClient.h"
43#include "api1/Camera2Client.h"
44#include "api_pro/ProCamera2Client.h"
45#include "api2/CameraDeviceClient.h"
46#include "utils/CameraTraces.h"
47#include "CameraDeviceFactory.h"
48
49namespace android {
50
51// ----------------------------------------------------------------------------
52// Logging support -- this is for debugging only
53// Use "adb shell dumpsys media.camera -v 1" to change it.
54volatile int32_t gLogLevel = 0;
55
56#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
57#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
58
59static void setLogLevel(int level) {
60    android_atomic_write(level, &gLogLevel);
61}
62
63// ----------------------------------------------------------------------------
64
65static int getCallingPid() {
66    return IPCThreadState::self()->getCallingPid();
67}
68
69static int getCallingUid() {
70    return IPCThreadState::self()->getCallingUid();
71}
72
73extern "C" {
74static void camera_device_status_change(
75        const struct camera_module_callbacks* callbacks,
76        int camera_id,
77        int new_status) {
78    sp<CameraService> cs = const_cast<CameraService*>(
79                                static_cast<const CameraService*>(callbacks));
80
81    cs->onDeviceStatusChanged(
82        camera_id,
83        new_status);
84}
85} // extern "C"
86
87// ----------------------------------------------------------------------------
88
89// This is ugly and only safe if we never re-create the CameraService, but
90// should be ok for now.
91static CameraService *gCameraService;
92
93CameraService::CameraService()
94    :mSoundRef(0), mModule(0)
95{
96    ALOGI("CameraService started (pid=%d)", getpid());
97    gCameraService = this;
98
99    for (size_t i = 0; i < MAX_CAMERAS; ++i) {
100        mStatusList[i] = ICameraServiceListener::STATUS_PRESENT;
101    }
102
103    this->camera_device_status_change = android::camera_device_status_change;
104}
105
106void CameraService::onFirstRef()
107{
108    LOG1("CameraService::onFirstRef");
109
110    BnCameraService::onFirstRef();
111
112    if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
113                (const hw_module_t **)&mModule) < 0) {
114        ALOGE("Could not load camera HAL module");
115        mNumberOfCameras = 0;
116    }
117    else {
118        ALOGI("Loaded \"%s\" camera module", mModule->common.name);
119        mNumberOfCameras = mModule->get_number_of_cameras();
120        if (mNumberOfCameras > MAX_CAMERAS) {
121            ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
122                    mNumberOfCameras, MAX_CAMERAS);
123            mNumberOfCameras = MAX_CAMERAS;
124        }
125        for (int i = 0; i < mNumberOfCameras; i++) {
126            setCameraFree(i);
127        }
128
129        if (mModule->common.module_api_version >=
130                CAMERA_MODULE_API_VERSION_2_1) {
131            mModule->set_callbacks(this);
132        }
133
134        CameraDeviceFactory::registerService(this);
135    }
136}
137
138CameraService::~CameraService() {
139    for (int i = 0; i < mNumberOfCameras; i++) {
140        if (mBusy[i]) {
141            ALOGE("camera %d is still in use in destructor!", i);
142        }
143    }
144
145    gCameraService = NULL;
146}
147
148void CameraService::onDeviceStatusChanged(int cameraId,
149                                          int newStatus)
150{
151    ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
152          cameraId, newStatus);
153
154    if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
155        ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
156        return;
157    }
158
159    if ((int)getStatus(cameraId) == newStatus) {
160        ALOGE("%s: State transition to the same status 0x%x not allowed",
161              __FUNCTION__, (uint32_t)newStatus);
162        return;
163    }
164
165    /* don't do this in updateStatus
166       since it is also called from connect and we could get into a deadlock */
167    if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
168        Vector<sp<BasicClient> > clientsToDisconnect;
169        {
170           Mutex::Autolock al(mServiceLock);
171
172           /* Find all clients that we need to disconnect */
173           sp<BasicClient> client = mClient[cameraId].promote();
174           if (client.get() != NULL) {
175               clientsToDisconnect.push_back(client);
176           }
177
178           int i = cameraId;
179           for (size_t j = 0; j < mProClientList[i].size(); ++j) {
180               sp<ProClient> cl = mProClientList[i][j].promote();
181               if (cl != NULL) {
182                   clientsToDisconnect.push_back(cl);
183               }
184           }
185        }
186
187        /* now disconnect them. don't hold the lock
188           or we can get into a deadlock */
189
190        for (size_t i = 0; i < clientsToDisconnect.size(); ++i) {
191            sp<BasicClient> client = clientsToDisconnect[i];
192
193            client->disconnect();
194            /**
195             * The remote app will no longer be able to call methods on the
196             * client since the client PID will be reset to 0
197             */
198        }
199
200        ALOGV("%s: After unplug, disconnected %d clients",
201              __FUNCTION__, clientsToDisconnect.size());
202    }
203
204    updateStatus(
205            static_cast<ICameraServiceListener::Status>(newStatus), cameraId);
206
207}
208
209int32_t CameraService::getNumberOfCameras() {
210    return mNumberOfCameras;
211}
212
213status_t CameraService::getCameraInfo(int cameraId,
214                                      struct CameraInfo* cameraInfo) {
215    if (!mModule) {
216        return -ENODEV;
217    }
218
219    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
220        return BAD_VALUE;
221    }
222
223    struct camera_info info;
224    status_t rc = mModule->get_camera_info(cameraId, &info);
225    cameraInfo->facing = info.facing;
226    cameraInfo->orientation = info.orientation;
227    return rc;
228}
229
230status_t CameraService::getCameraCharacteristics(int cameraId,
231                                                CameraMetadata* cameraInfo) {
232    if (!cameraInfo) {
233        ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
234        return BAD_VALUE;
235    }
236
237    if (!mModule) {
238        ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
239        return -ENODEV;
240    }
241
242    if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0) {
243        // TODO: Remove this check once HAL1 shim is in place.
244        ALOGE("%s: Only HAL module version V2 or higher supports static metadata", __FUNCTION__);
245        return BAD_VALUE;
246    }
247
248    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
249        ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
250        return BAD_VALUE;
251    }
252
253    int facing;
254    if (getDeviceVersion(cameraId, &facing) == CAMERA_DEVICE_API_VERSION_1_0) {
255        // TODO: Remove this check once HAL1 shim is in place.
256        ALOGE("%s: HAL1 doesn't support static metadata yet", __FUNCTION__);
257        return BAD_VALUE;
258    }
259
260    if (getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1) {
261        // Disable HAL2.x support for camera2 API for now.
262        ALOGW("%s: HAL2.x doesn't support getCameraCharacteristics for now", __FUNCTION__);
263        return BAD_VALUE;
264    }
265
266    struct camera_info info;
267    status_t ret = mModule->get_camera_info(cameraId, &info);
268    *cameraInfo = info.static_camera_characteristics;
269
270    return ret;
271}
272
273int CameraService::getDeviceVersion(int cameraId, int* facing) {
274    struct camera_info info;
275    if (mModule->get_camera_info(cameraId, &info) != OK) {
276        return -1;
277    }
278
279    int deviceVersion;
280    if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_0) {
281        deviceVersion = info.device_version;
282    } else {
283        deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
284    }
285
286    if (facing) {
287        *facing = info.facing;
288    }
289
290    return deviceVersion;
291}
292
293bool CameraService::isValidCameraId(int cameraId) {
294    int facing;
295    int deviceVersion = getDeviceVersion(cameraId, &facing);
296
297    switch(deviceVersion) {
298      case CAMERA_DEVICE_API_VERSION_1_0:
299      case CAMERA_DEVICE_API_VERSION_2_0:
300      case CAMERA_DEVICE_API_VERSION_2_1:
301      case CAMERA_DEVICE_API_VERSION_3_0:
302        return true;
303      default:
304        return false;
305    }
306
307    return false;
308}
309
310status_t CameraService::validateConnect(int cameraId,
311                                    /*inout*/
312                                    int& clientUid) const {
313
314    int callingPid = getCallingPid();
315
316    if (clientUid == USE_CALLING_UID) {
317        clientUid = getCallingUid();
318    } else {
319        // We only trust our own process to forward client UIDs
320        if (callingPid != getpid()) {
321            ALOGE("CameraService::connect X (pid %d) rejected (don't trust clientUid)",
322                    callingPid);
323            return PERMISSION_DENIED;
324        }
325    }
326
327    if (!mModule) {
328        ALOGE("Camera HAL module not loaded");
329        return -ENODEV;
330    }
331
332    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
333        ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
334            callingPid, cameraId);
335        return -ENODEV;
336    }
337
338    char value[PROPERTY_VALUE_MAX];
339    property_get("sys.secpolicy.camera.disabled", value, "0");
340    if (strcmp(value, "1") == 0) {
341        // Camera is disabled by DevicePolicyManager.
342        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
343        return -EACCES;
344    }
345
346    ICameraServiceListener::Status currentStatus = getStatus(cameraId);
347    if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
348        ALOGI("Camera is not plugged in,"
349               " connect X (pid %d) rejected", callingPid);
350        return -ENODEV;
351    } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
352        ALOGI("Camera is enumerating,"
353               " connect X (pid %d) rejected", callingPid);
354        return -EBUSY;
355    }
356    // Else don't check for STATUS_NOT_AVAILABLE.
357    //  -- It's done implicitly in canConnectUnsafe /w the mBusy array
358
359    return OK;
360}
361
362bool CameraService::canConnectUnsafe(int cameraId,
363                                     const String16& clientPackageName,
364                                     const sp<IBinder>& remoteCallback,
365                                     sp<BasicClient> &client) {
366    String8 clientName8(clientPackageName);
367    int callingPid = getCallingPid();
368
369    if (mClient[cameraId] != 0) {
370        client = mClient[cameraId].promote();
371        if (client != 0) {
372            if (remoteCallback == client->getRemote()) {
373                LOG1("CameraService::connect X (pid %d) (the same client)",
374                     callingPid);
375                return true;
376            } else {
377                // TODOSC: need to support 1 regular client,
378                // multiple shared clients here
379                ALOGW("CameraService::connect X (pid %d) rejected"
380                      " (existing client).", callingPid);
381                return false;
382            }
383        }
384        mClient[cameraId].clear();
385    }
386
387    /*
388    mBusy is set to false as the last step of the Client destructor,
389    after which it is guaranteed that the Client destructor has finished (
390    including any inherited destructors)
391
392    We only need this for a Client subclasses since we don't allow
393    multiple Clents to be opened concurrently, but multiple BasicClient
394    would be fine
395    */
396    if (mBusy[cameraId]) {
397        ALOGW("CameraService::connect X (pid %d, \"%s\") rejected"
398                " (camera %d is still busy).", callingPid,
399                clientName8.string(), cameraId);
400        return false;
401    }
402
403    return true;
404}
405
406status_t CameraService::connect(
407        const sp<ICameraClient>& cameraClient,
408        int cameraId,
409        const String16& clientPackageName,
410        int clientUid,
411        /*out*/
412        sp<ICamera>& device) {
413
414    String8 clientName8(clientPackageName);
415    int callingPid = getCallingPid();
416
417    LOG1("CameraService::connect E (pid %d \"%s\", id %d)", callingPid,
418            clientName8.string(), cameraId);
419
420    status_t status = validateConnect(cameraId, /*inout*/clientUid);
421    if (status != OK) {
422        return status;
423    }
424
425
426    sp<Client> client;
427    {
428        Mutex::Autolock lock(mServiceLock);
429        sp<BasicClient> clientTmp;
430        if (!canConnectUnsafe(cameraId, clientPackageName,
431                              cameraClient->asBinder(),
432                              /*out*/clientTmp)) {
433            return -EBUSY;
434        } else if (client.get() != NULL) {
435            device = static_cast<Client*>(clientTmp.get());
436            return OK;
437        }
438
439        int facing = -1;
440        int deviceVersion = getDeviceVersion(cameraId, &facing);
441
442        // If there are other non-exclusive users of the camera,
443        //  this will tear them down before we can reuse the camera
444        if (isValidCameraId(cameraId)) {
445            // transition from PRESENT -> NOT_AVAILABLE
446            updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
447                         cameraId);
448        }
449
450        switch(deviceVersion) {
451          case CAMERA_DEVICE_API_VERSION_1_0:
452            client = new CameraClient(this, cameraClient,
453                    clientPackageName, cameraId,
454                    facing, callingPid, clientUid, getpid());
455            break;
456          case CAMERA_DEVICE_API_VERSION_2_0:
457          case CAMERA_DEVICE_API_VERSION_2_1:
458          case CAMERA_DEVICE_API_VERSION_3_0:
459            client = new Camera2Client(this, cameraClient,
460                    clientPackageName, cameraId,
461                    facing, callingPid, clientUid, getpid(),
462                    deviceVersion);
463            break;
464          case -1:
465            ALOGE("Invalid camera id %d", cameraId);
466            return BAD_VALUE;
467          default:
468            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
469            return INVALID_OPERATION;
470        }
471
472        status_t status = connectFinishUnsafe(client, client->getRemote());
473        if (status != OK) {
474            // this is probably not recoverable.. maybe the client can try again
475            // OK: we can only get here if we were originally in PRESENT state
476            updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId);
477            return status;
478        }
479
480        mClient[cameraId] = client;
481        LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId,
482             getpid());
483    }
484    // important: release the mutex here so the client can call back
485    //    into the service from its destructor (can be at the end of the call)
486
487    device = client;
488    return OK;
489}
490
491status_t CameraService::connectFinishUnsafe(const sp<BasicClient>& client,
492                                            const sp<IBinder>& remoteCallback) {
493    status_t status = client->initialize(mModule);
494    if (status != OK) {
495        return status;
496    }
497
498    remoteCallback->linkToDeath(this);
499
500    return OK;
501}
502
503status_t CameraService::connectPro(
504                                        const sp<IProCameraCallbacks>& cameraCb,
505                                        int cameraId,
506                                        const String16& clientPackageName,
507                                        int clientUid,
508                                        /*out*/
509                                        sp<IProCameraUser>& device)
510{
511    String8 clientName8(clientPackageName);
512    int callingPid = getCallingPid();
513
514    LOG1("CameraService::connectPro E (pid %d \"%s\", id %d)", callingPid,
515            clientName8.string(), cameraId);
516    status_t status = validateConnect(cameraId, /*inout*/clientUid);
517    if (status != OK) {
518        return status;
519    }
520
521    sp<ProClient> client;
522    {
523        Mutex::Autolock lock(mServiceLock);
524        {
525            sp<BasicClient> client;
526            if (!canConnectUnsafe(cameraId, clientPackageName,
527                                  cameraCb->asBinder(),
528                                  /*out*/client)) {
529                return -EBUSY;
530            }
531        }
532
533        int facing = -1;
534        int deviceVersion = getDeviceVersion(cameraId, &facing);
535
536        switch(deviceVersion) {
537          case CAMERA_DEVICE_API_VERSION_1_0:
538            ALOGE("Camera id %d uses HALv1, doesn't support ProCamera",
539                  cameraId);
540            return -EOPNOTSUPP;
541            break;
542          case CAMERA_DEVICE_API_VERSION_2_0:
543          case CAMERA_DEVICE_API_VERSION_2_1:
544          case CAMERA_DEVICE_API_VERSION_3_0:
545            client = new ProCamera2Client(this, cameraCb, String16(),
546                    cameraId, facing, callingPid, USE_CALLING_UID, getpid());
547            break;
548          case -1:
549            ALOGE("Invalid camera id %d", cameraId);
550            return BAD_VALUE;
551          default:
552            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
553            return INVALID_OPERATION;
554        }
555
556        status_t status = connectFinishUnsafe(client, client->getRemote());
557        if (status != OK) {
558            return status;
559        }
560
561        mProClientList[cameraId].push(client);
562
563        LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId,
564                getpid());
565    }
566    // important: release the mutex here so the client can call back
567    //    into the service from its destructor (can be at the end of the call)
568    device = client;
569    return OK;
570}
571
572status_t CameraService::connectDevice(
573        const sp<ICameraDeviceCallbacks>& cameraCb,
574        int cameraId,
575        const String16& clientPackageName,
576        int clientUid,
577        /*out*/
578        sp<ICameraDeviceUser>& device)
579{
580
581    String8 clientName8(clientPackageName);
582    int callingPid = getCallingPid();
583
584    LOG1("CameraService::connectDevice E (pid %d \"%s\", id %d)", callingPid,
585            clientName8.string(), cameraId);
586
587    status_t status = validateConnect(cameraId, /*inout*/clientUid);
588    if (status != OK) {
589        return status;
590    }
591
592    sp<CameraDeviceClient> client;
593    {
594        Mutex::Autolock lock(mServiceLock);
595        {
596            sp<BasicClient> client;
597            if (!canConnectUnsafe(cameraId, clientPackageName,
598                                  cameraCb->asBinder(),
599                                  /*out*/client)) {
600                return -EBUSY;
601            }
602        }
603
604        int facing = -1;
605        int deviceVersion = getDeviceVersion(cameraId, &facing);
606
607        // If there are other non-exclusive users of the camera,
608        //  this will tear them down before we can reuse the camera
609        if (isValidCameraId(cameraId)) {
610            // transition from PRESENT -> NOT_AVAILABLE
611            updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
612                         cameraId);
613        }
614
615        switch(deviceVersion) {
616          case CAMERA_DEVICE_API_VERSION_1_0:
617            ALOGW("Camera using old HAL version: %d", deviceVersion);
618            return -EOPNOTSUPP;
619           // TODO: don't allow 2.0  Only allow 2.1 and higher
620          case CAMERA_DEVICE_API_VERSION_2_0:
621          case CAMERA_DEVICE_API_VERSION_2_1:
622          case CAMERA_DEVICE_API_VERSION_3_0:
623            client = new CameraDeviceClient(this, cameraCb, String16(),
624                    cameraId, facing, callingPid, USE_CALLING_UID, getpid());
625            break;
626          case -1:
627            ALOGE("Invalid camera id %d", cameraId);
628            return BAD_VALUE;
629          default:
630            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
631            return INVALID_OPERATION;
632        }
633
634        status_t status = connectFinishUnsafe(client, client->getRemote());
635        if (status != OK) {
636            // this is probably not recoverable.. maybe the client can try again
637            // OK: we can only get here if we were originally in PRESENT state
638            updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId);
639            return status;
640        }
641
642        LOG1("CameraService::connectDevice X (id %d, this pid is %d)", cameraId,
643                getpid());
644
645        mClient[cameraId] = client;
646    }
647    // important: release the mutex here so the client can call back
648    //    into the service from its destructor (can be at the end of the call)
649
650    device = client;
651    return OK;
652}
653
654
655status_t CameraService::addListener(
656                                const sp<ICameraServiceListener>& listener) {
657    ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
658
659    Mutex::Autolock lock(mServiceLock);
660
661    Vector<sp<ICameraServiceListener> >::iterator it, end;
662    for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
663        if ((*it)->asBinder() == listener->asBinder()) {
664            ALOGW("%s: Tried to add listener %p which was already subscribed",
665                  __FUNCTION__, listener.get());
666            return ALREADY_EXISTS;
667        }
668    }
669
670    mListenerList.push_back(listener);
671
672    /* Immediately signal current status to this listener only */
673    {
674        Mutex::Autolock m(mStatusMutex) ;
675        int numCams = getNumberOfCameras();
676        for (int i = 0; i < numCams; ++i) {
677            listener->onStatusChanged(mStatusList[i], i);
678        }
679    }
680
681    return OK;
682}
683status_t CameraService::removeListener(
684                                const sp<ICameraServiceListener>& listener) {
685    ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
686
687    Mutex::Autolock lock(mServiceLock);
688
689    Vector<sp<ICameraServiceListener> >::iterator it;
690    for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
691        if ((*it)->asBinder() == listener->asBinder()) {
692            mListenerList.erase(it);
693            return OK;
694        }
695    }
696
697    ALOGW("%s: Tried to remove a listener %p which was not subscribed",
698          __FUNCTION__, listener.get());
699
700    return BAD_VALUE;
701}
702
703void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) {
704    int callingPid = getCallingPid();
705    LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid);
706
707    // Declare this before the lock to make absolutely sure the
708    // destructor won't be called with the lock held.
709    Mutex::Autolock lock(mServiceLock);
710
711    int outIndex;
712    sp<BasicClient> client = findClientUnsafe(remoteBinder, outIndex);
713
714    if (client != 0) {
715        // Found our camera, clear and leave.
716        LOG1("removeClient: clear camera %d", outIndex);
717        mClient[outIndex].clear();
718
719        client->getRemote()->unlinkToDeath(this);
720    } else {
721
722        sp<ProClient> clientPro = findProClientUnsafe(remoteBinder);
723
724        if (clientPro != NULL) {
725            // Found our camera, clear and leave.
726            LOG1("removeClient: clear pro %p", clientPro.get());
727
728            clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this);
729        }
730    }
731
732    LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid);
733}
734
735sp<CameraService::ProClient> CameraService::findProClientUnsafe(
736                        const wp<IBinder>& cameraCallbacksRemote)
737{
738    sp<ProClient> clientPro;
739
740    for (int i = 0; i < mNumberOfCameras; ++i) {
741        Vector<size_t> removeIdx;
742
743        for (size_t j = 0; j < mProClientList[i].size(); ++j) {
744            wp<ProClient> cl = mProClientList[i][j];
745
746            sp<ProClient> clStrong = cl.promote();
747            if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) {
748                clientPro = clStrong;
749                break;
750            } else if (clStrong == NULL) {
751                // mark to clean up dead ptr
752                removeIdx.push(j);
753            }
754        }
755
756        // remove stale ptrs (in reverse so the indices dont change)
757        for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) {
758            mProClientList[i].removeAt(removeIdx[j]);
759        }
760
761    }
762
763    return clientPro;
764}
765
766sp<CameraService::BasicClient> CameraService::findClientUnsafe(
767                        const wp<IBinder>& cameraClient, int& outIndex) {
768    sp<BasicClient> client;
769
770    for (int i = 0; i < mNumberOfCameras; i++) {
771
772        // This happens when we have already disconnected (or this is
773        // just another unused camera).
774        if (mClient[i] == 0) continue;
775
776        // Promote mClient. It can fail if we are called from this path:
777        // Client::~Client() -> disconnect() -> removeClientByRemote().
778        client = mClient[i].promote();
779
780        // Clean up stale client entry
781        if (client == NULL) {
782            mClient[i].clear();
783            continue;
784        }
785
786        if (cameraClient == client->getRemote()) {
787            // Found our camera
788            outIndex = i;
789            return client;
790        }
791    }
792
793    outIndex = -1;
794    return NULL;
795}
796
797CameraService::BasicClient* CameraService::getClientByIdUnsafe(int cameraId) {
798    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
799    return mClient[cameraId].unsafe_get();
800}
801
802Mutex* CameraService::getClientLockById(int cameraId) {
803    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
804    return &mClientLock[cameraId];
805}
806
807sp<CameraService::BasicClient> CameraService::getClientByRemote(
808                                const wp<IBinder>& cameraClient) {
809
810    // Declare this before the lock to make absolutely sure the
811    // destructor won't be called with the lock held.
812    sp<BasicClient> client;
813
814    Mutex::Autolock lock(mServiceLock);
815
816    int outIndex;
817    client = findClientUnsafe(cameraClient, outIndex);
818
819    return client;
820}
821
822status_t CameraService::onTransact(
823    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
824    // Permission checks
825    switch (code) {
826        case BnCameraService::CONNECT:
827        case BnCameraService::CONNECT_PRO:
828            const int pid = getCallingPid();
829            const int self_pid = getpid();
830            if (pid != self_pid) {
831                // we're called from a different process, do the real check
832                if (!checkCallingPermission(
833                        String16("android.permission.CAMERA"))) {
834                    const int uid = getCallingUid();
835                    ALOGE("Permission Denial: "
836                         "can't use the camera pid=%d, uid=%d", pid, uid);
837                    return PERMISSION_DENIED;
838                }
839            }
840            break;
841    }
842
843    return BnCameraService::onTransact(code, data, reply, flags);
844}
845
846// The reason we need this busy bit is a new CameraService::connect() request
847// may come in while the previous Client's destructor has not been run or is
848// still running. If the last strong reference of the previous Client is gone
849// but the destructor has not been finished, we should not allow the new Client
850// to be created because we need to wait for the previous Client to tear down
851// the hardware first.
852void CameraService::setCameraBusy(int cameraId) {
853    android_atomic_write(1, &mBusy[cameraId]);
854
855    ALOGV("setCameraBusy cameraId=%d", cameraId);
856}
857
858void CameraService::setCameraFree(int cameraId) {
859    android_atomic_write(0, &mBusy[cameraId]);
860
861    ALOGV("setCameraFree cameraId=%d", cameraId);
862}
863
864// We share the media players for shutter and recording sound for all clients.
865// A reference count is kept to determine when we will actually release the
866// media players.
867
868MediaPlayer* CameraService::newMediaPlayer(const char *file) {
869    MediaPlayer* mp = new MediaPlayer();
870    if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
871        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
872        mp->prepare();
873    } else {
874        ALOGE("Failed to load CameraService sounds: %s", file);
875        return NULL;
876    }
877    return mp;
878}
879
880void CameraService::loadSound() {
881    Mutex::Autolock lock(mSoundLock);
882    LOG1("CameraService::loadSound ref=%d", mSoundRef);
883    if (mSoundRef++) return;
884
885    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
886    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
887}
888
889void CameraService::releaseSound() {
890    Mutex::Autolock lock(mSoundLock);
891    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
892    if (--mSoundRef) return;
893
894    for (int i = 0; i < NUM_SOUNDS; i++) {
895        if (mSoundPlayer[i] != 0) {
896            mSoundPlayer[i]->disconnect();
897            mSoundPlayer[i].clear();
898        }
899    }
900}
901
902void CameraService::playSound(sound_kind kind) {
903    LOG1("playSound(%d)", kind);
904    Mutex::Autolock lock(mSoundLock);
905    sp<MediaPlayer> player = mSoundPlayer[kind];
906    if (player != 0) {
907        player->seekTo(0);
908        player->start();
909    }
910}
911
912// ----------------------------------------------------------------------------
913
914CameraService::Client::Client(const sp<CameraService>& cameraService,
915        const sp<ICameraClient>& cameraClient,
916        const String16& clientPackageName,
917        int cameraId, int cameraFacing,
918        int clientPid, uid_t clientUid,
919        int servicePid) :
920        CameraService::BasicClient(cameraService, cameraClient->asBinder(),
921                clientPackageName,
922                cameraId, cameraFacing,
923                clientPid, clientUid,
924                servicePid)
925{
926    int callingPid = getCallingPid();
927    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
928
929    mRemoteCallback = cameraClient;
930
931    cameraService->setCameraBusy(cameraId);
932    cameraService->loadSound();
933
934    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
935}
936
937// tear down the client
938CameraService::Client::~Client() {
939    ALOGV("~Client");
940    mDestructionStarted = true;
941
942    mCameraService->releaseSound();
943    // unconditionally disconnect. function is idempotent
944    Client::disconnect();
945}
946
947CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
948        const sp<IBinder>& remoteCallback,
949        const String16& clientPackageName,
950        int cameraId, int cameraFacing,
951        int clientPid, uid_t clientUid,
952        int servicePid):
953        mClientPackageName(clientPackageName)
954{
955    mCameraService = cameraService;
956    mRemoteBinder = remoteCallback;
957    mCameraId = cameraId;
958    mCameraFacing = cameraFacing;
959    mClientPid = clientPid;
960    mClientUid = clientUid;
961    mServicePid = servicePid;
962    mOpsActive = false;
963    mDestructionStarted = false;
964}
965
966CameraService::BasicClient::~BasicClient() {
967    ALOGV("~BasicClient");
968    mDestructionStarted = true;
969}
970
971void CameraService::BasicClient::disconnect() {
972    ALOGV("BasicClient::disconnect");
973    mCameraService->removeClientByRemote(mRemoteBinder);
974    // client shouldn't be able to call into us anymore
975    mClientPid = 0;
976}
977
978status_t CameraService::BasicClient::startCameraOps() {
979    int32_t res;
980
981    mOpsCallback = new OpsCallback(this);
982
983    {
984        ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
985              __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
986    }
987
988    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
989            mClientPackageName, mOpsCallback);
990    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
991            mClientUid, mClientPackageName);
992
993    if (res != AppOpsManager::MODE_ALLOWED) {
994        ALOGI("Camera %d: Access for \"%s\" has been revoked",
995                mCameraId, String8(mClientPackageName).string());
996        return PERMISSION_DENIED;
997    }
998    mOpsActive = true;
999    return OK;
1000}
1001
1002status_t CameraService::BasicClient::finishCameraOps() {
1003    if (mOpsActive) {
1004        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1005                mClientPackageName);
1006        mOpsActive = false;
1007    }
1008    mAppOpsManager.stopWatchingMode(mOpsCallback);
1009    mOpsCallback.clear();
1010
1011    return OK;
1012}
1013
1014void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1015    String8 name(packageName);
1016    String8 myName(mClientPackageName);
1017
1018    if (op != AppOpsManager::OP_CAMERA) {
1019        ALOGW("Unexpected app ops notification received: %d", op);
1020        return;
1021    }
1022
1023    int32_t res;
1024    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1025            mClientUid, mClientPackageName);
1026    ALOGV("checkOp returns: %d, %s ", res,
1027            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1028            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1029            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1030            "UNKNOWN");
1031
1032    if (res != AppOpsManager::MODE_ALLOWED) {
1033        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1034                myName.string());
1035        // Reset the client PID to allow server-initiated disconnect,
1036        // and to prevent further calls by client.
1037        mClientPid = getCallingPid();
1038        notifyError();
1039        disconnect();
1040    }
1041}
1042
1043// ----------------------------------------------------------------------------
1044
1045Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
1046    return gCameraService->getClientLockById((int) user);
1047}
1048
1049// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
1050// be acquired for this to be safe
1051CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
1052    BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int) user);
1053    // OK: only CameraClient calls this, and they already cast anyway.
1054    Client* client = static_cast<Client*>(basicClient);
1055
1056    // This could happen if the Client is in the process of shutting down (the
1057    // last strong reference is gone, but the destructor hasn't finished
1058    // stopping the hardware).
1059    if (client == NULL) return NULL;
1060
1061    // destruction already started, so should not be accessed
1062    if (client->mDestructionStarted) return NULL;
1063
1064    return client;
1065}
1066
1067void CameraService::Client::notifyError() {
1068    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1069}
1070
1071// NOTE: function is idempotent
1072void CameraService::Client::disconnect() {
1073    ALOGV("Client::disconnect");
1074    BasicClient::disconnect();
1075    mCameraService->setCameraFree(mCameraId);
1076
1077    StatusVector rejectSourceStates;
1078    rejectSourceStates.push_back(ICameraServiceListener::STATUS_NOT_PRESENT);
1079    rejectSourceStates.push_back(ICameraServiceListener::STATUS_ENUMERATING);
1080
1081    // Transition to PRESENT if the camera is not in either of above 2 states
1082    mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
1083                                 mCameraId,
1084                                 &rejectSourceStates);
1085}
1086
1087CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1088        mClient(client) {
1089}
1090
1091void CameraService::Client::OpsCallback::opChanged(int32_t op,
1092        const String16& packageName) {
1093    sp<BasicClient> client = mClient.promote();
1094    if (client != NULL) {
1095        client->opChanged(op, packageName);
1096    }
1097}
1098
1099// ----------------------------------------------------------------------------
1100//                  IProCamera
1101// ----------------------------------------------------------------------------
1102
1103CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
1104        const sp<IProCameraCallbacks>& remoteCallback,
1105        const String16& clientPackageName,
1106        int cameraId,
1107        int cameraFacing,
1108        int clientPid,
1109        uid_t clientUid,
1110        int servicePid)
1111        : CameraService::BasicClient(cameraService, remoteCallback->asBinder(),
1112                clientPackageName, cameraId, cameraFacing,
1113                clientPid,  clientUid, servicePid)
1114{
1115    mRemoteCallback = remoteCallback;
1116}
1117
1118CameraService::ProClient::~ProClient() {
1119}
1120
1121void CameraService::ProClient::notifyError() {
1122    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1123}
1124
1125// ----------------------------------------------------------------------------
1126
1127static const int kDumpLockRetries = 50;
1128static const int kDumpLockSleep = 60000;
1129
1130static bool tryLock(Mutex& mutex)
1131{
1132    bool locked = false;
1133    for (int i = 0; i < kDumpLockRetries; ++i) {
1134        if (mutex.tryLock() == NO_ERROR) {
1135            locked = true;
1136            break;
1137        }
1138        usleep(kDumpLockSleep);
1139    }
1140    return locked;
1141}
1142
1143status_t CameraService::dump(int fd, const Vector<String16>& args) {
1144    String8 result;
1145    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1146        result.appendFormat("Permission Denial: "
1147                "can't dump CameraService from pid=%d, uid=%d\n",
1148                getCallingPid(),
1149                getCallingUid());
1150        write(fd, result.string(), result.size());
1151    } else {
1152        bool locked = tryLock(mServiceLock);
1153        // failed to lock - CameraService is probably deadlocked
1154        if (!locked) {
1155            result.append("CameraService may be deadlocked\n");
1156            write(fd, result.string(), result.size());
1157        }
1158
1159        bool hasClient = false;
1160        if (!mModule) {
1161            result = String8::format("No camera module available!\n");
1162            write(fd, result.string(), result.size());
1163            return NO_ERROR;
1164        }
1165
1166        result = String8::format("Camera module HAL API version: 0x%x\n",
1167                mModule->common.hal_api_version);
1168        result.appendFormat("Camera module API version: 0x%x\n",
1169                mModule->common.module_api_version);
1170        result.appendFormat("Camera module name: %s\n",
1171                mModule->common.name);
1172        result.appendFormat("Camera module author: %s\n",
1173                mModule->common.author);
1174        result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
1175        write(fd, result.string(), result.size());
1176        for (int i = 0; i < mNumberOfCameras; i++) {
1177            result = String8::format("Camera %d static information:\n", i);
1178            camera_info info;
1179
1180            status_t rc = mModule->get_camera_info(i, &info);
1181            if (rc != OK) {
1182                result.appendFormat("  Error reading static information!\n");
1183                write(fd, result.string(), result.size());
1184            } else {
1185                result.appendFormat("  Facing: %s\n",
1186                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
1187                result.appendFormat("  Orientation: %d\n", info.orientation);
1188                int deviceVersion;
1189                if (mModule->common.module_api_version <
1190                        CAMERA_MODULE_API_VERSION_2_0) {
1191                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
1192                } else {
1193                    deviceVersion = info.device_version;
1194                }
1195                result.appendFormat("  Device version: 0x%x\n", deviceVersion);
1196                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
1197                    result.appendFormat("  Device static metadata:\n");
1198                    write(fd, result.string(), result.size());
1199                    dump_indented_camera_metadata(info.static_camera_characteristics,
1200                            fd, 2, 4);
1201                } else {
1202                    write(fd, result.string(), result.size());
1203                }
1204            }
1205
1206            sp<BasicClient> client = mClient[i].promote();
1207            if (client == 0) {
1208                result = String8::format("  Device is closed, no client instance\n");
1209                write(fd, result.string(), result.size());
1210                continue;
1211            }
1212            hasClient = true;
1213            result = String8::format("  Device is open. Client instance dump:\n");
1214            write(fd, result.string(), result.size());
1215            client->dump(fd, args);
1216        }
1217        if (!hasClient) {
1218            result = String8::format("\nNo active camera clients yet.\n");
1219            write(fd, result.string(), result.size());
1220        }
1221
1222        if (locked) mServiceLock.unlock();
1223
1224        // Dump camera traces if there were any
1225        write(fd, "\n", 1);
1226        camera3::CameraTraces::dump(fd, args);
1227
1228        // change logging level
1229        int n = args.size();
1230        for (int i = 0; i + 1 < n; i++) {
1231            String16 verboseOption("-v");
1232            if (args[i] == verboseOption) {
1233                String8 levelStr(args[i+1]);
1234                int level = atoi(levelStr.string());
1235                result = String8::format("\nSetting log level to %d.\n", level);
1236                setLogLevel(level);
1237                write(fd, result.string(), result.size());
1238            }
1239        }
1240
1241    }
1242    return NO_ERROR;
1243}
1244
1245/*virtual*/void CameraService::binderDied(
1246    const wp<IBinder> &who) {
1247
1248    /**
1249      * While tempting to promote the wp<IBinder> into a sp,
1250      * it's actually not supported by the binder driver
1251      */
1252
1253    ALOGV("java clients' binder died");
1254
1255    sp<BasicClient> cameraClient = getClientByRemote(who);
1256
1257    if (cameraClient == 0) {
1258        ALOGV("java clients' binder death already cleaned up (normal case)");
1259        return;
1260    }
1261
1262    ALOGW("Disconnecting camera client %p since the binder for it "
1263          "died (this pid %d)", cameraClient.get(), getCallingPid());
1264
1265    cameraClient->disconnect();
1266
1267}
1268
1269void CameraService::updateStatus(ICameraServiceListener::Status status,
1270                                 int32_t cameraId,
1271                                 const StatusVector *rejectSourceStates) {
1272    // do not lock mServiceLock here or can get into a deadlock from
1273    //  connect() -> ProClient::disconnect -> updateStatus
1274    Mutex::Autolock lock(mStatusMutex);
1275
1276    ICameraServiceListener::Status oldStatus = mStatusList[cameraId];
1277
1278    mStatusList[cameraId] = status;
1279
1280    if (oldStatus != status) {
1281        ALOGV("%s: Status has changed for camera ID %d from 0x%x to 0x%x",
1282              __FUNCTION__, cameraId, (uint32_t)oldStatus, (uint32_t)status);
1283
1284        if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
1285            (status != ICameraServiceListener::STATUS_PRESENT &&
1286             status != ICameraServiceListener::STATUS_ENUMERATING)) {
1287
1288            ALOGW("%s: From NOT_PRESENT can only transition into PRESENT"
1289                  " or ENUMERATING", __FUNCTION__);
1290            mStatusList[cameraId] = oldStatus;
1291            return;
1292        }
1293
1294        if (rejectSourceStates != NULL) {
1295            const StatusVector &rejectList = *rejectSourceStates;
1296            StatusVector::const_iterator it = rejectList.begin();
1297
1298            /**
1299             * Sometimes we want to conditionally do a transition.
1300             * For example if a client disconnects, we want to go to PRESENT
1301             * only if we weren't already in NOT_PRESENT or ENUMERATING.
1302             */
1303            for (; it != rejectList.end(); ++it) {
1304                if (oldStatus == *it) {
1305                    ALOGV("%s: Rejecting status transition for Camera ID %d, "
1306                          " since the source state was was in one of the bad "
1307                          " states.", __FUNCTION__, cameraId);
1308                    mStatusList[cameraId] = oldStatus;
1309                    return;
1310                }
1311            }
1312        }
1313
1314        /**
1315          * ProClients lose their exclusive lock.
1316          * - Done before the CameraClient can initialize the HAL device,
1317          *   since we want to be able to close it before they get to initialize
1318          */
1319        if (status == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1320            Vector<wp<ProClient> > proClients(mProClientList[cameraId]);
1321            Vector<wp<ProClient> >::const_iterator it;
1322
1323            for (it = proClients.begin(); it != proClients.end(); ++it) {
1324                sp<ProClient> proCl = it->promote();
1325                if (proCl.get() != NULL) {
1326                    proCl->onExclusiveLockStolen();
1327                }
1328            }
1329        }
1330
1331        Vector<sp<ICameraServiceListener> >::const_iterator it;
1332        for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
1333            (*it)->onStatusChanged(status, cameraId);
1334        }
1335    }
1336}
1337
1338ICameraServiceListener::Status CameraService::getStatus(int cameraId) const {
1339    if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
1340        ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId);
1341        return ICameraServiceListener::STATUS_UNKNOWN;
1342    }
1343
1344    Mutex::Autolock al(mStatusMutex);
1345    return mStatusList[cameraId];
1346}
1347
1348}; // namespace android
1349