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