CameraService.cpp revision 152dbcf2e0d8a46691e22b102972540640f054ec
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, String16(),
795                    cameraId, facing, callingPid, USE_CALLING_UID, 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, String16(),
875                    cameraId, facing, callingPid, USE_CALLING_UID, 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            const int pid = getCallingPid();
1094            const int self_pid = getpid();
1095            if (pid != self_pid) {
1096                // we're called from a different process, do the real check
1097                if (!checkCallingPermission(
1098                        String16("android.permission.CAMERA"))) {
1099                    const int uid = getCallingUid();
1100                    ALOGE("Permission Denial: "
1101                         "can't use the camera pid=%d, uid=%d", pid, uid);
1102                    return PERMISSION_DENIED;
1103                }
1104            }
1105            break;
1106    }
1107
1108    return BnCameraService::onTransact(code, data, reply, flags);
1109}
1110
1111// The reason we need this busy bit is a new CameraService::connect() request
1112// may come in while the previous Client's destructor has not been run or is
1113// still running. If the last strong reference of the previous Client is gone
1114// but the destructor has not been finished, we should not allow the new Client
1115// to be created because we need to wait for the previous Client to tear down
1116// the hardware first.
1117void CameraService::setCameraBusy(int cameraId) {
1118    android_atomic_write(1, &mBusy[cameraId]);
1119
1120    ALOGV("setCameraBusy cameraId=%d", cameraId);
1121}
1122
1123void CameraService::setCameraFree(int cameraId) {
1124    android_atomic_write(0, &mBusy[cameraId]);
1125
1126    ALOGV("setCameraFree cameraId=%d", cameraId);
1127}
1128
1129// We share the media players for shutter and recording sound for all clients.
1130// A reference count is kept to determine when we will actually release the
1131// media players.
1132
1133MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1134    MediaPlayer* mp = new MediaPlayer();
1135    if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1136        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1137        mp->prepare();
1138    } else {
1139        ALOGE("Failed to load CameraService sounds: %s", file);
1140        return NULL;
1141    }
1142    return mp;
1143}
1144
1145void CameraService::loadSound() {
1146    Mutex::Autolock lock(mSoundLock);
1147    LOG1("CameraService::loadSound ref=%d", mSoundRef);
1148    if (mSoundRef++) return;
1149
1150    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1151    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1152}
1153
1154void CameraService::releaseSound() {
1155    Mutex::Autolock lock(mSoundLock);
1156    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1157    if (--mSoundRef) return;
1158
1159    for (int i = 0; i < NUM_SOUNDS; i++) {
1160        if (mSoundPlayer[i] != 0) {
1161            mSoundPlayer[i]->disconnect();
1162            mSoundPlayer[i].clear();
1163        }
1164    }
1165}
1166
1167void CameraService::playSound(sound_kind kind) {
1168    LOG1("playSound(%d)", kind);
1169    Mutex::Autolock lock(mSoundLock);
1170    sp<MediaPlayer> player = mSoundPlayer[kind];
1171    if (player != 0) {
1172        player->seekTo(0);
1173        player->start();
1174    }
1175}
1176
1177// ----------------------------------------------------------------------------
1178
1179CameraService::Client::Client(const sp<CameraService>& cameraService,
1180        const sp<ICameraClient>& cameraClient,
1181        const String16& clientPackageName,
1182        int cameraId, int cameraFacing,
1183        int clientPid, uid_t clientUid,
1184        int servicePid) :
1185        CameraService::BasicClient(cameraService, cameraClient->asBinder(),
1186                clientPackageName,
1187                cameraId, cameraFacing,
1188                clientPid, clientUid,
1189                servicePid)
1190{
1191    int callingPid = getCallingPid();
1192    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1193
1194    mRemoteCallback = cameraClient;
1195
1196    cameraService->setCameraBusy(cameraId);
1197    cameraService->loadSound();
1198
1199    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1200}
1201
1202// tear down the client
1203CameraService::Client::~Client() {
1204    ALOGV("~Client");
1205    mDestructionStarted = true;
1206
1207    mCameraService->releaseSound();
1208    // unconditionally disconnect. function is idempotent
1209    Client::disconnect();
1210}
1211
1212CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1213        const sp<IBinder>& remoteCallback,
1214        const String16& clientPackageName,
1215        int cameraId, int cameraFacing,
1216        int clientPid, uid_t clientUid,
1217        int servicePid):
1218        mClientPackageName(clientPackageName)
1219{
1220    mCameraService = cameraService;
1221    mRemoteBinder = remoteCallback;
1222    mCameraId = cameraId;
1223    mCameraFacing = cameraFacing;
1224    mClientPid = clientPid;
1225    mClientUid = clientUid;
1226    mServicePid = servicePid;
1227    mOpsActive = false;
1228    mDestructionStarted = false;
1229}
1230
1231CameraService::BasicClient::~BasicClient() {
1232    ALOGV("~BasicClient");
1233    mDestructionStarted = true;
1234}
1235
1236void CameraService::BasicClient::disconnect() {
1237    ALOGV("BasicClient::disconnect");
1238    mCameraService->removeClientByRemote(mRemoteBinder);
1239    // client shouldn't be able to call into us anymore
1240    mClientPid = 0;
1241}
1242
1243status_t CameraService::BasicClient::startCameraOps() {
1244    int32_t res;
1245
1246    mOpsCallback = new OpsCallback(this);
1247
1248    {
1249        ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1250              __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1251    }
1252
1253    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1254            mClientPackageName, mOpsCallback);
1255    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1256            mClientUid, mClientPackageName);
1257
1258    if (res != AppOpsManager::MODE_ALLOWED) {
1259        ALOGI("Camera %d: Access for \"%s\" has been revoked",
1260                mCameraId, String8(mClientPackageName).string());
1261        return PERMISSION_DENIED;
1262    }
1263    mOpsActive = true;
1264    return OK;
1265}
1266
1267status_t CameraService::BasicClient::finishCameraOps() {
1268    if (mOpsActive) {
1269        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1270                mClientPackageName);
1271        mOpsActive = false;
1272    }
1273    mAppOpsManager.stopWatchingMode(mOpsCallback);
1274    mOpsCallback.clear();
1275
1276    return OK;
1277}
1278
1279void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1280    String8 name(packageName);
1281    String8 myName(mClientPackageName);
1282
1283    if (op != AppOpsManager::OP_CAMERA) {
1284        ALOGW("Unexpected app ops notification received: %d", op);
1285        return;
1286    }
1287
1288    int32_t res;
1289    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1290            mClientUid, mClientPackageName);
1291    ALOGV("checkOp returns: %d, %s ", res,
1292            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1293            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1294            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1295            "UNKNOWN");
1296
1297    if (res != AppOpsManager::MODE_ALLOWED) {
1298        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1299                myName.string());
1300        // Reset the client PID to allow server-initiated disconnect,
1301        // and to prevent further calls by client.
1302        mClientPid = getCallingPid();
1303        CaptureResultExtras resultExtras; // a dummy result (invalid)
1304        notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
1305        disconnect();
1306    }
1307}
1308
1309// ----------------------------------------------------------------------------
1310
1311Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
1312    return gCameraService->getClientLockById((int)(intptr_t) user);
1313}
1314
1315// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
1316// be acquired for this to be safe
1317CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
1318    BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int)(intptr_t) user);
1319    // OK: only CameraClient calls this, and they already cast anyway.
1320    Client* client = static_cast<Client*>(basicClient);
1321
1322    // This could happen if the Client is in the process of shutting down (the
1323    // last strong reference is gone, but the destructor hasn't finished
1324    // stopping the hardware).
1325    if (client == NULL) return NULL;
1326
1327    // destruction already started, so should not be accessed
1328    if (client->mDestructionStarted) return NULL;
1329
1330    return client;
1331}
1332
1333void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1334        const CaptureResultExtras& resultExtras) {
1335    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1336}
1337
1338// NOTE: function is idempotent
1339void CameraService::Client::disconnect() {
1340    ALOGV("Client::disconnect");
1341    BasicClient::disconnect();
1342    mCameraService->setCameraFree(mCameraId);
1343
1344    StatusVector rejectSourceStates;
1345    rejectSourceStates.push_back(ICameraServiceListener::STATUS_NOT_PRESENT);
1346    rejectSourceStates.push_back(ICameraServiceListener::STATUS_ENUMERATING);
1347
1348    // Transition to PRESENT if the camera is not in either of above 2 states
1349    mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
1350                                 mCameraId,
1351                                 &rejectSourceStates);
1352}
1353
1354CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1355        mClient(client) {
1356}
1357
1358void CameraService::Client::OpsCallback::opChanged(int32_t op,
1359        const String16& packageName) {
1360    sp<BasicClient> client = mClient.promote();
1361    if (client != NULL) {
1362        client->opChanged(op, packageName);
1363    }
1364}
1365
1366// ----------------------------------------------------------------------------
1367//                  IProCamera
1368// ----------------------------------------------------------------------------
1369
1370CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
1371        const sp<IProCameraCallbacks>& remoteCallback,
1372        const String16& clientPackageName,
1373        int cameraId,
1374        int cameraFacing,
1375        int clientPid,
1376        uid_t clientUid,
1377        int servicePid)
1378        : CameraService::BasicClient(cameraService, remoteCallback->asBinder(),
1379                clientPackageName, cameraId, cameraFacing,
1380                clientPid,  clientUid, servicePid)
1381{
1382    mRemoteCallback = remoteCallback;
1383}
1384
1385CameraService::ProClient::~ProClient() {
1386}
1387
1388void CameraService::ProClient::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1389        const CaptureResultExtras& resultExtras) {
1390    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1391}
1392
1393// ----------------------------------------------------------------------------
1394
1395static const int kDumpLockRetries = 50;
1396static const int kDumpLockSleep = 60000;
1397
1398static bool tryLock(Mutex& mutex)
1399{
1400    bool locked = false;
1401    for (int i = 0; i < kDumpLockRetries; ++i) {
1402        if (mutex.tryLock() == NO_ERROR) {
1403            locked = true;
1404            break;
1405        }
1406        usleep(kDumpLockSleep);
1407    }
1408    return locked;
1409}
1410
1411status_t CameraService::dump(int fd, const Vector<String16>& args) {
1412    String8 result;
1413    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1414        result.appendFormat("Permission Denial: "
1415                "can't dump CameraService from pid=%d, uid=%d\n",
1416                getCallingPid(),
1417                getCallingUid());
1418        write(fd, result.string(), result.size());
1419    } else {
1420        bool locked = tryLock(mServiceLock);
1421        // failed to lock - CameraService is probably deadlocked
1422        if (!locked) {
1423            result.append("CameraService may be deadlocked\n");
1424            write(fd, result.string(), result.size());
1425        }
1426
1427        bool hasClient = false;
1428        if (!mModule) {
1429            result = String8::format("No camera module available!\n");
1430            write(fd, result.string(), result.size());
1431            if (locked) mServiceLock.unlock();
1432            return NO_ERROR;
1433        }
1434
1435        result = String8::format("Camera module HAL API version: 0x%x\n",
1436                mModule->common.hal_api_version);
1437        result.appendFormat("Camera module API version: 0x%x\n",
1438                mModule->common.module_api_version);
1439        result.appendFormat("Camera module name: %s\n",
1440                mModule->common.name);
1441        result.appendFormat("Camera module author: %s\n",
1442                mModule->common.author);
1443        result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
1444
1445        sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1446        if (desc == NULL) {
1447            result.appendFormat("Vendor tags left unimplemented.\n");
1448        } else {
1449            result.appendFormat("Vendor tag definitions:\n");
1450        }
1451
1452        write(fd, result.string(), result.size());
1453
1454        if (desc != NULL) {
1455            desc->dump(fd, /*verbosity*/2, /*indentation*/4);
1456        }
1457
1458        for (int i = 0; i < mNumberOfCameras; i++) {
1459            result = String8::format("Camera %d static information:\n", i);
1460            camera_info info;
1461
1462            status_t rc = mModule->get_camera_info(i, &info);
1463            if (rc != OK) {
1464                result.appendFormat("  Error reading static information!\n");
1465                write(fd, result.string(), result.size());
1466            } else {
1467                result.appendFormat("  Facing: %s\n",
1468                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
1469                result.appendFormat("  Orientation: %d\n", info.orientation);
1470                int deviceVersion;
1471                if (mModule->common.module_api_version <
1472                        CAMERA_MODULE_API_VERSION_2_0) {
1473                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
1474                } else {
1475                    deviceVersion = info.device_version;
1476                }
1477                result.appendFormat("  Device version: 0x%x\n", deviceVersion);
1478                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
1479                    result.appendFormat("  Device static metadata:\n");
1480                    write(fd, result.string(), result.size());
1481                    dump_indented_camera_metadata(info.static_camera_characteristics,
1482                            fd, /*verbosity*/2, /*indentation*/4);
1483                } else {
1484                    write(fd, result.string(), result.size());
1485                }
1486            }
1487
1488            sp<BasicClient> client = mClient[i].promote();
1489            if (client == 0) {
1490                result = String8::format("  Device is closed, no client instance\n");
1491                write(fd, result.string(), result.size());
1492                continue;
1493            }
1494            hasClient = true;
1495            result = String8::format("  Device is open. Client instance dump:\n");
1496            write(fd, result.string(), result.size());
1497            client->dump(fd, args);
1498        }
1499        if (!hasClient) {
1500            result = String8::format("\nNo active camera clients yet.\n");
1501            write(fd, result.string(), result.size());
1502        }
1503
1504        if (locked) mServiceLock.unlock();
1505
1506        // Dump camera traces if there were any
1507        write(fd, "\n", 1);
1508        camera3::CameraTraces::dump(fd, args);
1509
1510        // change logging level
1511        int n = args.size();
1512        for (int i = 0; i + 1 < n; i++) {
1513            String16 verboseOption("-v");
1514            if (args[i] == verboseOption) {
1515                String8 levelStr(args[i+1]);
1516                int level = atoi(levelStr.string());
1517                result = String8::format("\nSetting log level to %d.\n", level);
1518                setLogLevel(level);
1519                write(fd, result.string(), result.size());
1520            }
1521        }
1522
1523    }
1524    return NO_ERROR;
1525}
1526
1527/*virtual*/void CameraService::binderDied(
1528    const wp<IBinder> &who) {
1529
1530    /**
1531      * While tempting to promote the wp<IBinder> into a sp,
1532      * it's actually not supported by the binder driver
1533      */
1534
1535    ALOGV("java clients' binder died");
1536
1537    sp<BasicClient> cameraClient = getClientByRemote(who);
1538
1539    if (cameraClient == 0) {
1540        ALOGV("java clients' binder death already cleaned up (normal case)");
1541        return;
1542    }
1543
1544    ALOGW("Disconnecting camera client %p since the binder for it "
1545          "died (this pid %d)", cameraClient.get(), getCallingPid());
1546
1547    cameraClient->disconnect();
1548
1549}
1550
1551void CameraService::updateStatus(ICameraServiceListener::Status status,
1552                                 int32_t cameraId,
1553                                 const StatusVector *rejectSourceStates) {
1554    // do not lock mServiceLock here or can get into a deadlock from
1555    //  connect() -> ProClient::disconnect -> updateStatus
1556    Mutex::Autolock lock(mStatusMutex);
1557
1558    ICameraServiceListener::Status oldStatus = mStatusList[cameraId];
1559
1560    mStatusList[cameraId] = status;
1561
1562    if (oldStatus != status) {
1563        ALOGV("%s: Status has changed for camera ID %d from 0x%x to 0x%x",
1564              __FUNCTION__, cameraId, (uint32_t)oldStatus, (uint32_t)status);
1565
1566        if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
1567            (status != ICameraServiceListener::STATUS_PRESENT &&
1568             status != ICameraServiceListener::STATUS_ENUMERATING)) {
1569
1570            ALOGW("%s: From NOT_PRESENT can only transition into PRESENT"
1571                  " or ENUMERATING", __FUNCTION__);
1572            mStatusList[cameraId] = oldStatus;
1573            return;
1574        }
1575
1576        if (rejectSourceStates != NULL) {
1577            const StatusVector &rejectList = *rejectSourceStates;
1578            StatusVector::const_iterator it = rejectList.begin();
1579
1580            /**
1581             * Sometimes we want to conditionally do a transition.
1582             * For example if a client disconnects, we want to go to PRESENT
1583             * only if we weren't already in NOT_PRESENT or ENUMERATING.
1584             */
1585            for (; it != rejectList.end(); ++it) {
1586                if (oldStatus == *it) {
1587                    ALOGV("%s: Rejecting status transition for Camera ID %d, "
1588                          " since the source state was was in one of the bad "
1589                          " states.", __FUNCTION__, cameraId);
1590                    mStatusList[cameraId] = oldStatus;
1591                    return;
1592                }
1593            }
1594        }
1595
1596        /**
1597          * ProClients lose their exclusive lock.
1598          * - Done before the CameraClient can initialize the HAL device,
1599          *   since we want to be able to close it before they get to initialize
1600          */
1601        if (status == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1602            Vector<wp<ProClient> > proClients(mProClientList[cameraId]);
1603            Vector<wp<ProClient> >::const_iterator it;
1604
1605            for (it = proClients.begin(); it != proClients.end(); ++it) {
1606                sp<ProClient> proCl = it->promote();
1607                if (proCl.get() != NULL) {
1608                    proCl->onExclusiveLockStolen();
1609                }
1610            }
1611        }
1612
1613        Vector<sp<ICameraServiceListener> >::const_iterator it;
1614        for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
1615            (*it)->onStatusChanged(status, cameraId);
1616        }
1617    }
1618}
1619
1620ICameraServiceListener::Status CameraService::getStatus(int cameraId) const {
1621    if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
1622        ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId);
1623        return ICameraServiceListener::STATUS_UNKNOWN;
1624    }
1625
1626    Mutex::Autolock al(mStatusMutex);
1627    return mStatusList[cameraId];
1628}
1629
1630}; // namespace android
1631