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