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