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