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