CameraService.cpp revision 98a668f6ea51e4d894d2ebb61a0e18287fb14008
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 ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
21#include <algorithm>
22#include <climits>
23#include <stdio.h>
24#include <cstring>
25#include <ctime>
26#include <string>
27#include <sys/types.h>
28#include <inttypes.h>
29#include <pthread.h>
30
31#include <binder/AppOpsManager.h>
32#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryBase.h>
35#include <binder/MemoryHeapBase.h>
36#include <binder/ProcessInfoService.h>
37#include <cutils/atomic.h>
38#include <cutils/properties.h>
39#include <gui/Surface.h>
40#include <hardware/hardware.h>
41#include <media/AudioSystem.h>
42#include <media/IMediaHTTPService.h>
43#include <media/mediaplayer.h>
44#include <mediautils/BatteryNotifier.h>
45#include <utils/Errors.h>
46#include <utils/Log.h>
47#include <utils/String16.h>
48#include <utils/Trace.h>
49#include <private/android_filesystem_config.h>
50#include <system/camera_vendor_tags.h>
51#include <system/camera_metadata.h>
52#include <system/camera.h>
53
54#include "CameraService.h"
55#include "api1/CameraClient.h"
56#include "api1/Camera2Client.h"
57#include "api2/CameraDeviceClient.h"
58#include "utils/CameraTraces.h"
59
60namespace android {
61
62// ----------------------------------------------------------------------------
63// Logging support -- this is for debugging only
64// Use "adb shell dumpsys media.camera -v 1" to change it.
65volatile int32_t gLogLevel = 0;
66
67#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
68#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
69
70static void setLogLevel(int level) {
71    android_atomic_write(level, &gLogLevel);
72}
73
74// ----------------------------------------------------------------------------
75
76extern "C" {
77static void camera_device_status_change(
78        const struct camera_module_callbacks* callbacks,
79        int camera_id,
80        int new_status) {
81    sp<CameraService> cs = const_cast<CameraService*>(
82            static_cast<const CameraService*>(callbacks));
83
84    cs->onDeviceStatusChanged(static_cast<camera_device_status_t>(camera_id),
85            static_cast<camera_device_status_t>(new_status));
86}
87
88static void torch_mode_status_change(
89        const struct camera_module_callbacks* callbacks,
90        const char* camera_id,
91        int new_status) {
92    if (!callbacks || !camera_id) {
93        ALOGE("%s invalid parameters. callbacks %p, camera_id %p", __FUNCTION__,
94                callbacks, camera_id);
95    }
96    sp<CameraService> cs = const_cast<CameraService*>(
97                                static_cast<const CameraService*>(callbacks));
98
99    ICameraServiceListener::TorchStatus status;
100    switch (new_status) {
101        case TORCH_MODE_STATUS_NOT_AVAILABLE:
102            status = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
103            break;
104        case TORCH_MODE_STATUS_AVAILABLE_OFF:
105            status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
106            break;
107        case TORCH_MODE_STATUS_AVAILABLE_ON:
108            status = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
109            break;
110        default:
111            ALOGE("Unknown torch status %d", new_status);
112            return;
113    }
114
115    cs->onTorchStatusChanged(
116        String8(camera_id),
117        status);
118}
119} // extern "C"
120
121// ----------------------------------------------------------------------------
122
123// This is ugly and only safe if we never re-create the CameraService, but
124// should be ok for now.
125static CameraService *gCameraService;
126
127CameraService::CameraService() :
128        mEventLog(DEFAULT_EVENT_LOG_LENGTH),
129        mSoundRef(0), mModule(nullptr),
130        mNumberOfCameras(0), mNumberOfNormalCameras(0) {
131    ALOGI("CameraService started (pid=%d)", getpid());
132    gCameraService = this;
133
134    this->camera_device_status_change = android::camera_device_status_change;
135    this->torch_mode_status_change = android::torch_mode_status_change;
136
137    mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
138}
139
140void CameraService::onFirstRef()
141{
142    ALOGI("CameraService process starting");
143
144    BnCameraService::onFirstRef();
145
146    // Update battery life tracking if service is restarting
147    BatteryNotifier& notifier(BatteryNotifier::getInstance());
148    notifier.noteResetCamera();
149    notifier.noteResetFlashlight();
150
151    camera_module_t *rawModule;
152    int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,
153            (const hw_module_t **)&rawModule);
154    if (err < 0) {
155        ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
156        logServiceError("Could not load camera HAL module", err);
157        return;
158    }
159
160    mModule = new CameraModule(rawModule);
161    err = mModule->init();
162    if (err != OK) {
163        ALOGE("Could not initialize camera HAL module: %d (%s)", err,
164            strerror(-err));
165        logServiceError("Could not initialize camera HAL module", err);
166
167        delete mModule;
168        mModule = nullptr;
169        return;
170    }
171    ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());
172
173    mNumberOfCameras = mModule->getNumberOfCameras();
174    mNumberOfNormalCameras = mNumberOfCameras;
175
176    // Setup vendor tags before we call get_camera_info the first time
177    // because HAL might need to setup static vendor keys in get_camera_info
178    VendorTagDescriptor::clearGlobalVendorTagDescriptor();
179    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) {
180        setUpVendorTags();
181    }
182
183    mFlashlight = new CameraFlashlight(*mModule, *this);
184    status_t res = mFlashlight->findFlashUnits();
185    if (res) {
186        // impossible because we haven't open any camera devices.
187        ALOGE("Failed to find flash units.");
188    }
189
190    int latestStrangeCameraId = INT_MAX;
191    for (int i = 0; i < mNumberOfCameras; i++) {
192        String8 cameraId = String8::format("%d", i);
193
194        // Get camera info
195
196        struct camera_info info;
197        bool haveInfo = true;
198        status_t rc = mModule->getCameraInfo(i, &info);
199        if (rc != NO_ERROR) {
200            ALOGE("%s: Received error loading camera info for device %d, cost and"
201                    " conflicting devices fields set to defaults for this device.",
202                    __FUNCTION__, i);
203            haveInfo = false;
204        }
205
206        // Check for backwards-compatibility support
207        if (haveInfo) {
208            if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
209                delete mModule;
210                mModule = nullptr;
211                return;
212            }
213        }
214
215        // Defaults to use for cost and conflicting devices
216        int cost = 100;
217        char** conflicting_devices = nullptr;
218        size_t conflicting_devices_length = 0;
219
220        // If using post-2.4 module version, query the cost + conflicting devices from the HAL
221        if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo) {
222            cost = info.resource_cost;
223            conflicting_devices = info.conflicting_devices;
224            conflicting_devices_length = info.conflicting_devices_length;
225        }
226
227        std::set<String8> conflicting;
228        for (size_t i = 0; i < conflicting_devices_length; i++) {
229            conflicting.emplace(String8(conflicting_devices[i]));
230        }
231
232        // Initialize state for each camera device
233        {
234            Mutex::Autolock lock(mCameraStatesLock);
235            mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost,
236                    conflicting));
237        }
238
239        if (mFlashlight->hasFlashUnit(cameraId)) {
240            mTorchStatusMap.add(cameraId,
241                    ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
242        }
243    }
244
245    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) {
246        mModule->setCallbacks(this);
247    }
248
249    CameraService::pingCameraServiceProxy();
250}
251
252sp<ICameraServiceProxy> CameraService::getCameraServiceProxy() {
253    sp<IServiceManager> sm = defaultServiceManager();
254    sp<IBinder> binder = sm->getService(String16("media.camera.proxy"));
255    if (binder == nullptr) {
256        return nullptr;
257    }
258    sp<ICameraServiceProxy> proxyBinder = interface_cast<ICameraServiceProxy>(binder);
259    return proxyBinder;
260}
261
262void CameraService::pingCameraServiceProxy() {
263    sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
264    if (proxyBinder == nullptr) return;
265    proxyBinder->pingForUserUpdate();
266}
267
268CameraService::~CameraService() {
269    if (mModule) {
270        delete mModule;
271        mModule = nullptr;
272    }
273    VendorTagDescriptor::clearGlobalVendorTagDescriptor();
274    gCameraService = nullptr;
275}
276
277void CameraService::onDeviceStatusChanged(camera_device_status_t  cameraId,
278        camera_device_status_t newStatus) {
279    ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
280          cameraId, newStatus);
281
282    String8 id = String8::format("%d", cameraId);
283    std::shared_ptr<CameraState> state = getCameraState(id);
284
285    if (state == nullptr) {
286        ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
287        return;
288    }
289
290    ICameraServiceListener::Status oldStatus = state->getStatus();
291
292    if (oldStatus == static_cast<ICameraServiceListener::Status>(newStatus)) {
293        ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
294        return;
295    }
296
297    if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
298        logDeviceRemoved(id, String8::format("Device status changed from %d to %d", oldStatus,
299                newStatus));
300        sp<BasicClient> clientToDisconnect;
301        {
302            // Don't do this in updateStatus to avoid deadlock over mServiceLock
303            Mutex::Autolock lock(mServiceLock);
304
305            // Set the device status to NOT_PRESENT, clients will no longer be able to connect
306            // to this device until the status changes
307            updateStatus(ICameraServiceListener::STATUS_NOT_PRESENT, id);
308
309            // Remove cached shim parameters
310            state->setShimParams(CameraParameters());
311
312            // Remove the client from the list of active clients
313            clientToDisconnect = removeClientLocked(id);
314
315            // Notify the client of disconnection
316            clientToDisconnect->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
317                    CaptureResultExtras{});
318        }
319
320        ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
321                __FUNCTION__, id.string());
322
323        // Disconnect client
324        if (clientToDisconnect.get() != nullptr) {
325            // Ensure not in binder RPC so client disconnect PID checks work correctly
326            LOG_ALWAYS_FATAL_IF(getCallingPid() != getpid(),
327                    "onDeviceStatusChanged must be called from the camera service process!");
328            clientToDisconnect->disconnect();
329        }
330
331    } else {
332        if (oldStatus == ICameraServiceListener::Status::STATUS_NOT_PRESENT) {
333            logDeviceAdded(id, String8::format("Device status changed from %d to %d", oldStatus,
334                    newStatus));
335        }
336        updateStatus(static_cast<ICameraServiceListener::Status>(newStatus), id);
337    }
338
339}
340
341void CameraService::onTorchStatusChanged(const String8& cameraId,
342        ICameraServiceListener::TorchStatus newStatus) {
343    Mutex::Autolock al(mTorchStatusMutex);
344    onTorchStatusChangedLocked(cameraId, newStatus);
345}
346
347void CameraService::onTorchStatusChangedLocked(const String8& cameraId,
348        ICameraServiceListener::TorchStatus newStatus) {
349    ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
350            __FUNCTION__, cameraId.string(), newStatus);
351
352    ICameraServiceListener::TorchStatus status;
353    status_t res = getTorchStatusLocked(cameraId, &status);
354    if (res) {
355        ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
356                __FUNCTION__, cameraId.string(), strerror(-res), res);
357        return;
358    }
359    if (status == newStatus) {
360        return;
361    }
362
363    res = setTorchStatusLocked(cameraId, newStatus);
364    if (res) {
365        ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
366                (uint32_t)newStatus, strerror(-res), res);
367        return;
368    }
369
370    {
371        // Update battery life logging for flashlight
372        Mutex::Autolock al(mTorchUidMapMutex);
373        auto iter = mTorchUidMap.find(cameraId);
374        if (iter != mTorchUidMap.end()) {
375            int oldUid = iter->second.second;
376            int newUid = iter->second.first;
377            BatteryNotifier& notifier(BatteryNotifier::getInstance());
378            if (oldUid != newUid) {
379                // If the UID has changed, log the status and update current UID in mTorchUidMap
380                if (status == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
381                    notifier.noteFlashlightOff(cameraId, oldUid);
382                }
383                if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
384                    notifier.noteFlashlightOn(cameraId, newUid);
385                }
386                iter->second.second = newUid;
387            } else {
388                // If the UID has not changed, log the status
389                if (newStatus == ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON) {
390                    notifier.noteFlashlightOn(cameraId, oldUid);
391                } else {
392                    notifier.noteFlashlightOff(cameraId, oldUid);
393                }
394            }
395        }
396    }
397
398    {
399        Mutex::Autolock lock(mStatusListenerLock);
400        for (auto& i : mListenerList) {
401            i->onTorchStatusChanged(newStatus, String16{cameraId});
402        }
403    }
404}
405
406int32_t CameraService::getNumberOfCameras() {
407    ATRACE_CALL();
408    return getNumberOfCameras(CAMERA_TYPE_BACKWARD_COMPATIBLE);
409}
410
411int32_t CameraService::getNumberOfCameras(int type) {
412    ATRACE_CALL();
413    switch (type) {
414        case CAMERA_TYPE_BACKWARD_COMPATIBLE:
415            return mNumberOfNormalCameras;
416        case CAMERA_TYPE_ALL:
417            return mNumberOfCameras;
418        default:
419            ALOGW("%s: Unknown camera type %d, returning 0",
420                    __FUNCTION__, type);
421            return 0;
422    }
423}
424
425status_t CameraService::getCameraInfo(int cameraId,
426                                      struct CameraInfo* cameraInfo) {
427    ATRACE_CALL();
428    if (!mModule) {
429        return -ENODEV;
430    }
431
432    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
433        return BAD_VALUE;
434    }
435
436    struct camera_info info;
437    status_t rc = filterGetInfoErrorCode(
438        mModule->getCameraInfo(cameraId, &info));
439    cameraInfo->facing = info.facing;
440    cameraInfo->orientation = info.orientation;
441    return rc;
442}
443
444int CameraService::cameraIdToInt(const String8& cameraId) {
445    errno = 0;
446    size_t pos = 0;
447    int ret = stoi(std::string{cameraId.string()}, &pos);
448    if (errno != 0 || pos != cameraId.size()) {
449        return -1;
450    }
451    return ret;
452}
453
454status_t CameraService::generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo) {
455    ATRACE_CALL();
456    status_t ret = OK;
457    struct CameraInfo info;
458    if ((ret = getCameraInfo(cameraId, &info)) != OK) {
459        return ret;
460    }
461
462    CameraMetadata shimInfo;
463    int32_t orientation = static_cast<int32_t>(info.orientation);
464    if ((ret = shimInfo.update(ANDROID_SENSOR_ORIENTATION, &orientation, 1)) != OK) {
465        return ret;
466    }
467
468    uint8_t facing = (info.facing == CAMERA_FACING_FRONT) ?
469            ANDROID_LENS_FACING_FRONT : ANDROID_LENS_FACING_BACK;
470    if ((ret = shimInfo.update(ANDROID_LENS_FACING, &facing, 1)) != OK) {
471        return ret;
472    }
473
474    CameraParameters shimParams;
475    if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
476        // Error logged by callee
477        return ret;
478    }
479
480    Vector<Size> sizes;
481    Vector<Size> jpegSizes;
482    Vector<int32_t> formats;
483    {
484        shimParams.getSupportedPreviewSizes(/*out*/sizes);
485        shimParams.getSupportedPreviewFormats(/*out*/formats);
486        shimParams.getSupportedPictureSizes(/*out*/jpegSizes);
487    }
488
489    // Always include IMPLEMENTATION_DEFINED
490    formats.add(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED);
491
492    const size_t INTS_PER_CONFIG = 4;
493
494    // Build available stream configurations metadata
495    size_t streamConfigSize = (sizes.size() * formats.size() + jpegSizes.size()) * INTS_PER_CONFIG;
496
497    Vector<int32_t> streamConfigs;
498    streamConfigs.setCapacity(streamConfigSize);
499
500    for (size_t i = 0; i < formats.size(); ++i) {
501        for (size_t j = 0; j < sizes.size(); ++j) {
502            streamConfigs.add(formats[i]);
503            streamConfigs.add(sizes[j].width);
504            streamConfigs.add(sizes[j].height);
505            streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
506        }
507    }
508
509    for (size_t i = 0; i < jpegSizes.size(); ++i) {
510        streamConfigs.add(HAL_PIXEL_FORMAT_BLOB);
511        streamConfigs.add(jpegSizes[i].width);
512        streamConfigs.add(jpegSizes[i].height);
513        streamConfigs.add(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT);
514    }
515
516    if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
517            streamConfigs.array(), streamConfigSize)) != OK) {
518        return ret;
519    }
520
521    int64_t fakeMinFrames[0];
522    // TODO: Fixme, don't fake min frame durations.
523    if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
524            fakeMinFrames, 0)) != OK) {
525        return ret;
526    }
527
528    int64_t fakeStalls[0];
529    // TODO: Fixme, don't fake stall durations.
530    if ((ret = shimInfo.update(ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
531            fakeStalls, 0)) != OK) {
532        return ret;
533    }
534
535    *cameraInfo = shimInfo;
536    return OK;
537}
538
539status_t CameraService::getCameraCharacteristics(int cameraId,
540                                                CameraMetadata* cameraInfo) {
541    ATRACE_CALL();
542    if (!cameraInfo) {
543        ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
544        return BAD_VALUE;
545    }
546
547    if (!mModule) {
548        ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
549        return -ENODEV;
550    }
551
552    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
553        ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
554        return BAD_VALUE;
555    }
556
557    int facing;
558    status_t ret = OK;
559    if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0 ||
560            getDeviceVersion(cameraId, &facing) < CAMERA_DEVICE_API_VERSION_3_0) {
561        /**
562         * Backwards compatibility mode for old HALs:
563         * - Convert CameraInfo into static CameraMetadata properties.
564         * - Retrieve cached CameraParameters for this camera.  If none exist,
565         *   attempt to open CameraClient and retrieve the CameraParameters.
566         * - Convert cached CameraParameters into static CameraMetadata
567         *   properties.
568         */
569        ALOGI("%s: Switching to HAL1 shim implementation...", __FUNCTION__);
570
571        if ((ret = generateShimMetadata(cameraId, cameraInfo)) != OK) {
572            return ret;
573        }
574
575    } else {
576        /**
577         * Normal HAL 2.1+ codepath.
578         */
579        struct camera_info info;
580        ret = filterGetInfoErrorCode(mModule->getCameraInfo(cameraId, &info));
581        *cameraInfo = info.static_camera_characteristics;
582    }
583
584    return ret;
585}
586
587int CameraService::getCallingPid() {
588    return IPCThreadState::self()->getCallingPid();
589}
590
591int CameraService::getCallingUid() {
592    return IPCThreadState::self()->getCallingUid();
593}
594
595String8 CameraService::getFormattedCurrentTime() {
596    time_t now = time(nullptr);
597    char formattedTime[64];
598    strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
599    return String8(formattedTime);
600}
601
602int CameraService::getCameraPriorityFromProcState(int procState) {
603    // Find the priority for the camera usage based on the process state.  Higher priority clients
604    // win for evictions.
605    if (procState < 0) {
606        ALOGE("%s: Received invalid process state %d from ActivityManagerService!", __FUNCTION__,
607                procState);
608        return -1;
609    }
610    // Treat sleeping TOP processes the same as regular TOP processes, for
611    // access priority.  This is important for lock-screen camera launch scenarios
612    if (procState == PROCESS_STATE_TOP_SLEEPING) {
613        procState = PROCESS_STATE_TOP;
614    }
615    return INT_MAX - procState;
616}
617
618status_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
619    ATRACE_CALL();
620    if (!mModule) {
621        ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
622        return -ENODEV;
623    }
624
625    desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
626    return OK;
627}
628
629int CameraService::getDeviceVersion(int cameraId, int* facing) {
630    ATRACE_CALL();
631    struct camera_info info;
632    if (mModule->getCameraInfo(cameraId, &info) != OK) {
633        return -1;
634    }
635
636    int deviceVersion;
637    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
638        deviceVersion = info.device_version;
639    } else {
640        deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
641    }
642
643    if (facing) {
644        *facing = info.facing;
645    }
646
647    return deviceVersion;
648}
649
650status_t CameraService::filterGetInfoErrorCode(status_t err) {
651    switch(err) {
652        case NO_ERROR:
653        case -EINVAL:
654            return err;
655        default:
656            break;
657    }
658    return -ENODEV;
659}
660
661bool CameraService::setUpVendorTags() {
662    ATRACE_CALL();
663    vendor_tag_ops_t vOps = vendor_tag_ops_t();
664
665    // Check if vendor operations have been implemented
666    if (!mModule->isVendorTagDefined()) {
667        ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
668        return false;
669    }
670
671    mModule->getVendorTagOps(&vOps);
672
673    // Ensure all vendor operations are present
674    if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
675            vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
676            vOps.get_tag_type == NULL) {
677        ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
678               , __FUNCTION__);
679        return false;
680    }
681
682    // Read all vendor tag definitions into a descriptor
683    sp<VendorTagDescriptor> desc;
684    status_t res;
685    if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
686            != OK) {
687        ALOGE("%s: Could not generate descriptor from vendor tag operations,"
688              "received error %s (%d). Camera clients will not be able to use"
689              "vendor tags", __FUNCTION__, strerror(res), res);
690        return false;
691    }
692
693    // Set the global descriptor to use with camera metadata
694    VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
695    return true;
696}
697
698status_t CameraService::makeClient(const sp<CameraService>& cameraService,
699        const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
700        int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
701        int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
702        /*out*/sp<BasicClient>* client) {
703
704    // TODO: Update CameraClients + HAL interface to use strings for Camera IDs
705    int id = cameraIdToInt(cameraId);
706    if (id == -1) {
707        ALOGE("%s: Invalid camera ID %s, cannot convert to integer.", __FUNCTION__,
708                cameraId.string());
709        return BAD_VALUE;
710    }
711
712    if (halVersion < 0 || halVersion == deviceVersion) {
713        // Default path: HAL version is unspecified by caller, create CameraClient
714        // based on device version reported by the HAL.
715        switch(deviceVersion) {
716          case CAMERA_DEVICE_API_VERSION_1_0:
717            if (effectiveApiLevel == API_1) {  // Camera1 API route
718                sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
719                *client = new CameraClient(cameraService, tmp, packageName, id, facing,
720                        clientPid, clientUid, getpid(), legacyMode);
721            } else { // Camera2 API route
722                ALOGW("Camera using old HAL version: %d", deviceVersion);
723                return -EOPNOTSUPP;
724            }
725            break;
726          case CAMERA_DEVICE_API_VERSION_3_0:
727          case CAMERA_DEVICE_API_VERSION_3_1:
728          case CAMERA_DEVICE_API_VERSION_3_2:
729          case CAMERA_DEVICE_API_VERSION_3_3:
730            if (effectiveApiLevel == API_1) { // Camera1 API route
731                sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
732                *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
733                        clientPid, clientUid, servicePid, legacyMode);
734            } else { // Camera2 API route
735                sp<ICameraDeviceCallbacks> tmp =
736                        static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
737                *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
738                        facing, clientPid, clientUid, servicePid);
739            }
740            break;
741          default:
742            // Should not be reachable
743            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
744            return INVALID_OPERATION;
745        }
746    } else {
747        // A particular HAL version is requested by caller. Create CameraClient
748        // based on the requested HAL version.
749        if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
750            halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
751            // Only support higher HAL version device opened as HAL1.0 device.
752            sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
753            *client = new CameraClient(cameraService, tmp, packageName, id, facing,
754                    clientPid, clientUid, servicePid, legacyMode);
755        } else {
756            // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
757            ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
758                    " opened as HAL %x device", halVersion, deviceVersion,
759                    CAMERA_DEVICE_API_VERSION_1_0);
760            return INVALID_OPERATION;
761        }
762    }
763    return NO_ERROR;
764}
765
766String8 CameraService::toString(std::set<userid_t> intSet) {
767    String8 s("");
768    bool first = true;
769    for (userid_t i : intSet) {
770        if (first) {
771            s.appendFormat("%d", i);
772            first = false;
773        } else {
774            s.appendFormat(", %d", i);
775        }
776    }
777    return s;
778}
779
780status_t CameraService::initializeShimMetadata(int cameraId) {
781    int uid = getCallingUid();
782
783    String16 internalPackageName("cameraserver");
784    String8 id = String8::format("%d", cameraId);
785    status_t ret = NO_ERROR;
786    sp<Client> tmp = nullptr;
787    if ((ret = connectHelper<ICameraClient,Client>(sp<ICameraClient>{nullptr}, id,
788            static_cast<int>(CAMERA_HAL_API_VERSION_UNSPECIFIED), internalPackageName, uid,
789            USE_CALLING_PID, API_1, false, true, tmp)) != NO_ERROR) {
790        ALOGE("%s: Error %d (%s) initializing shim metadata.", __FUNCTION__, ret, strerror(ret));
791        return ret;
792    }
793    return NO_ERROR;
794}
795
796status_t CameraService::getLegacyParametersLazy(int cameraId,
797        /*out*/
798        CameraParameters* parameters) {
799
800    ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
801
802    status_t ret = 0;
803
804    if (parameters == NULL) {
805        ALOGE("%s: parameters must not be null", __FUNCTION__);
806        return BAD_VALUE;
807    }
808
809    String8 id = String8::format("%d", cameraId);
810
811    // Check if we already have parameters
812    {
813        // Scope for service lock
814        Mutex::Autolock lock(mServiceLock);
815        auto cameraState = getCameraState(id);
816        if (cameraState == nullptr) {
817            ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
818            return BAD_VALUE;
819        }
820        CameraParameters p = cameraState->getShimParams();
821        if (!p.isEmpty()) {
822            *parameters = p;
823            return NO_ERROR;
824        }
825    }
826
827    int64_t token = IPCThreadState::self()->clearCallingIdentity();
828    ret = initializeShimMetadata(cameraId);
829    IPCThreadState::self()->restoreCallingIdentity(token);
830    if (ret != NO_ERROR) {
831        // Error already logged by callee
832        return ret;
833    }
834
835    // Check for parameters again
836    {
837        // Scope for service lock
838        Mutex::Autolock lock(mServiceLock);
839        auto cameraState = getCameraState(id);
840        if (cameraState == nullptr) {
841            ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, id.string());
842            return BAD_VALUE;
843        }
844        CameraParameters p = cameraState->getShimParams();
845        if (!p.isEmpty()) {
846            *parameters = p;
847            return NO_ERROR;
848        }
849    }
850
851    ALOGE("%s: Parameters were not initialized, or were empty.  Device may not be present.",
852            __FUNCTION__);
853    return INVALID_OPERATION;
854}
855
856// Can camera service trust the caller based on the calling UID?
857static bool isTrustedCallingUid(uid_t uid) {
858    switch (uid) {
859        case AID_MEDIA:         // mediaserver
860        case AID_CAMERASERVER: // cameraserver
861            return true;
862        default:
863            return false;
864    }
865}
866
867status_t CameraService::validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid,
868        /*inout*/int& clientPid) const {
869
870    int callingPid = getCallingPid();
871    int callingUid = getCallingUid();
872
873    // Check if we can trust clientUid
874    if (clientUid == USE_CALLING_UID) {
875        clientUid = callingUid;
876    } else if (!isTrustedCallingUid(callingUid)) {
877        ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
878                "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
879        return PERMISSION_DENIED;
880    }
881
882    // Check if we can trust clientPid
883    if (clientPid == USE_CALLING_PID) {
884        clientPid = callingPid;
885    } else if (!isTrustedCallingUid(callingUid)) {
886        ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
887                "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
888        return PERMISSION_DENIED;
889    }
890
891    // If it's not calling from cameraserver, check the permission.
892    if (callingPid != getpid() &&
893            !checkPermission(String16("android.permission.CAMERA"), clientPid, clientUid)) {
894        ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
895        return PERMISSION_DENIED;
896    }
897
898    // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
899    // connected to camera service directly.
900    clientPid = callingPid;
901
902    if (!mModule) {
903        ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
904                callingPid);
905        return -ENODEV;
906    }
907
908    if (getCameraState(cameraId) == nullptr) {
909        ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
910                cameraId.string());
911        return -ENODEV;
912    }
913
914    userid_t clientUserId = multiuser_get_user_id(clientUid);
915
916    // Only allow clients who are being used by the current foreground device user, unless calling
917    // from our own process.
918    if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
919        ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
920                "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
921                toString(mAllowedUsers).string());
922        return PERMISSION_DENIED;
923    }
924
925    return checkIfDeviceIsUsable(cameraId);
926}
927
928status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
929    auto cameraState = getCameraState(cameraId);
930    int callingPid = getCallingPid();
931    if (cameraState == nullptr) {
932        ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
933                cameraId.string());
934        return -ENODEV;
935    }
936
937    ICameraServiceListener::Status currentStatus = cameraState->getStatus();
938    if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
939        ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
940                callingPid, cameraId.string());
941        return -ENODEV;
942    } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
943        ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
944                callingPid, cameraId.string());
945        return -EBUSY;
946    }
947
948    return NO_ERROR;
949}
950
951void CameraService::finishConnectLocked(const sp<BasicClient>& client,
952        const CameraService::DescriptorPtr& desc) {
953
954    // Make a descriptor for the incoming client
955    auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
956    auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
957
958    logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
959            String8(client->getPackageName()));
960
961    if (evicted.size() > 0) {
962        // This should never happen - clients should already have been removed in disconnect
963        for (auto& i : evicted) {
964            ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
965                    __FUNCTION__, i->getKey().string());
966        }
967
968        LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
969                __FUNCTION__);
970    }
971
972    // And register a death notification for the client callback. Do
973    // this last to avoid Binder policy where a nested Binder
974    // transaction might be pre-empted to service the client death
975    // notification if the client process dies before linkToDeath is
976    // invoked.
977    sp<IBinder> remoteCallback = client->getRemote();
978    if (remoteCallback != nullptr) {
979        remoteCallback->linkToDeath(this);
980    }
981}
982
983status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
984        apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
985        /*out*/
986        sp<BasicClient>* client,
987        std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
988    ATRACE_CALL();
989    status_t ret = NO_ERROR;
990    std::vector<DescriptorPtr> evictedClients;
991    DescriptorPtr clientDescriptor;
992    {
993        if (effectiveApiLevel == API_1) {
994            // If we are using API1, any existing client for this camera ID with the same remote
995            // should be returned rather than evicted to allow MediaRecorder to work properly.
996
997            auto current = mActiveClientManager.get(cameraId);
998            if (current != nullptr) {
999                auto clientSp = current->getValue();
1000                if (clientSp.get() != nullptr) { // should never be needed
1001                    if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
1002                        ALOGW("CameraService connect called from same client, but with a different"
1003                                " API level, evicting prior client...");
1004                    } else if (clientSp->getRemote() == remoteCallback) {
1005                        ALOGI("CameraService::connect X (PID %d) (second call from same"
1006                                " app binder, returning the same client)", clientPid);
1007                        *client = clientSp;
1008                        return NO_ERROR;
1009                    }
1010                }
1011            }
1012        }
1013
1014        // Return error if the device was unplugged or removed by the HAL for some reason
1015        if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1016            return ret;
1017        }
1018
1019        // Get current active client PIDs
1020        std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1021        ownerPids.push_back(clientPid);
1022
1023        // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1024        // address of PROCESS_STATE_NONEXISTENT as a reference argument
1025        // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1026        // not have an out-of-class definition.
1027        std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
1028
1029        // Get priorites of all active PIDs
1030        ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1031                /*out*/&priorities[0]);
1032
1033        // Update all active clients' priorities
1034        std::map<int,int> pidToPriorityMap;
1035        for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1036            pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1037        }
1038        mActiveClientManager.updatePriorities(pidToPriorityMap);
1039
1040        // Get state for the given cameraId
1041        auto state = getCameraState(cameraId);
1042        if (state == nullptr) {
1043            ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1044                clientPid, cameraId.string());
1045            return BAD_VALUE;
1046        }
1047
1048        // Make descriptor for incoming client
1049        clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1050                sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1051                state->getConflicting(),
1052                getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1053
1054        // Find clients that would be evicted
1055        auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1056
1057        // If the incoming client was 'evicted,' higher priority clients have the camera in the
1058        // background, so we cannot do evictions
1059        if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1060            ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1061                    " priority).", clientPid);
1062
1063            sp<BasicClient> clientSp = clientDescriptor->getValue();
1064            String8 curTime = getFormattedCurrentTime();
1065            auto incompatibleClients =
1066                    mActiveClientManager.getIncompatibleClients(clientDescriptor);
1067
1068            String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
1069                    "(PID %d, priority %d) due to eviction policy", curTime.string(),
1070                    cameraId.string(), packageName.string(), clientPid,
1071                    getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1072
1073            for (auto& i : incompatibleClients) {
1074                msg.appendFormat("\n   - Blocked by existing device %s client for package %s"
1075                        "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1076                        String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1077                        i->getPriority());
1078                ALOGE("   Conflicts with: Device %s, client package %s (PID %"
1079                        PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1080                        String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1081                        i->getPriority());
1082            }
1083
1084            // Log the client's attempt
1085            Mutex::Autolock l(mLogLock);
1086            mEventLog.add(msg);
1087
1088            return -EBUSY;
1089        }
1090
1091        for (auto& i : evicted) {
1092            sp<BasicClient> clientSp = i->getValue();
1093            if (clientSp.get() == nullptr) {
1094                ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1095
1096                // TODO: Remove this
1097                LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1098                        __FUNCTION__);
1099                mActiveClientManager.remove(i);
1100                continue;
1101            }
1102
1103            ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1104                    i->getKey().string());
1105            evictedClients.push_back(i);
1106
1107            // Log the clients evicted
1108            logEvent(String8::format("EVICT device %s client held by package %s (PID"
1109                    " %" PRId32 ", priority %" PRId32 ")\n   - Evicted by device %s client for"
1110                    " package %s (PID %d, priority %" PRId32 ")",
1111                    i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1112                    i->getOwnerId(), i->getPriority(), cameraId.string(),
1113                    packageName.string(), clientPid,
1114                    getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1115
1116            // Notify the client of disconnection
1117            clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1118                    CaptureResultExtras());
1119        }
1120    }
1121
1122    // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1123    // other clients from connecting in mServiceLockWrapper if held
1124    mServiceLock.unlock();
1125
1126    // Clear caller identity temporarily so client disconnect PID checks work correctly
1127    int64_t token = IPCThreadState::self()->clearCallingIdentity();
1128
1129    // Destroy evicted clients
1130    for (auto& i : evictedClients) {
1131        // Disconnect is blocking, and should only have returned when HAL has cleaned up
1132        i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1133    }
1134
1135    IPCThreadState::self()->restoreCallingIdentity(token);
1136
1137    for (const auto& i : evictedClients) {
1138        ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1139                __FUNCTION__, i->getKey().string(), i->getOwnerId());
1140        ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1141        if (ret == TIMED_OUT) {
1142            ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1143                    "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1144                    mActiveClientManager.toString().string());
1145            return -EBUSY;
1146        }
1147        if (ret != NO_ERROR) {
1148            ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1149                    "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1150                    ret, mActiveClientManager.toString().string());
1151            return ret;
1152        }
1153    }
1154
1155    evictedClients.clear();
1156
1157    // Once clients have been disconnected, relock
1158    mServiceLock.lock();
1159
1160    // Check again if the device was unplugged or something while we weren't holding mServiceLock
1161    if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1162        return ret;
1163    }
1164
1165    *partial = clientDescriptor;
1166    return NO_ERROR;
1167}
1168
1169status_t CameraService::connect(
1170        const sp<ICameraClient>& cameraClient,
1171        int cameraId,
1172        const String16& clientPackageName,
1173        int clientUid,
1174        int clientPid,
1175        /*out*/
1176        sp<ICamera>& device) {
1177
1178    ATRACE_CALL();
1179    status_t ret = NO_ERROR;
1180    String8 id = String8::format("%d", cameraId);
1181    sp<Client> client = nullptr;
1182    ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
1183            clientPackageName, clientUid, clientPid, API_1, false, false, /*out*/client);
1184
1185    if(ret != NO_ERROR) {
1186        logRejected(id, getCallingPid(), String8(clientPackageName),
1187                String8::format("%s (%d)", strerror(-ret), ret));
1188        return ret;
1189    }
1190
1191    device = client;
1192    return NO_ERROR;
1193}
1194
1195status_t CameraService::connectLegacy(
1196        const sp<ICameraClient>& cameraClient,
1197        int cameraId, int halVersion,
1198        const String16& clientPackageName,
1199        int clientUid,
1200        /*out*/
1201        sp<ICamera>& device) {
1202
1203    ATRACE_CALL();
1204    String8 id = String8::format("%d", cameraId);
1205    int apiVersion = mModule->getModuleApiVersion();
1206    if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
1207            apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
1208        /*
1209         * Either the HAL version is unspecified in which case this just creates
1210         * a camera client selected by the latest device version, or
1211         * it's a particular version in which case the HAL must supported
1212         * the open_legacy call
1213         */
1214        ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
1215                __FUNCTION__, apiVersion);
1216        logRejected(id, getCallingPid(), String8(clientPackageName),
1217                String8("HAL module version doesn't support legacy HAL connections"));
1218        return INVALID_OPERATION;
1219    }
1220
1221    status_t ret = NO_ERROR;
1222    sp<Client> client = nullptr;
1223    ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1224            clientUid, USE_CALLING_PID, API_1, true, false, /*out*/client);
1225
1226    if(ret != NO_ERROR) {
1227        logRejected(id, getCallingPid(), String8(clientPackageName),
1228                String8::format("%s (%d)", strerror(-ret), ret));
1229        return ret;
1230    }
1231
1232    device = client;
1233    return NO_ERROR;
1234}
1235
1236status_t CameraService::connectDevice(
1237        const sp<ICameraDeviceCallbacks>& cameraCb,
1238        int cameraId,
1239        const String16& clientPackageName,
1240        int clientUid,
1241        /*out*/
1242        sp<ICameraDeviceUser>& device) {
1243
1244    ATRACE_CALL();
1245    status_t ret = NO_ERROR;
1246    String8 id = String8::format("%d", cameraId);
1247    sp<CameraDeviceClient> client = nullptr;
1248    ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1249            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, USE_CALLING_PID,
1250            API_2, false, false, /*out*/client);
1251
1252    if(ret != NO_ERROR) {
1253        logRejected(id, getCallingPid(), String8(clientPackageName),
1254                String8::format("%s (%d)", strerror(-ret), ret));
1255        return ret;
1256    }
1257
1258    device = client;
1259    return NO_ERROR;
1260}
1261
1262status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1263        const sp<IBinder>& clientBinder) {
1264
1265    ATRACE_CALL();
1266    if (enabled && clientBinder == nullptr) {
1267        ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1268        return -EINVAL;
1269    }
1270
1271    String8 id = String8(cameraId.string());
1272    int uid = getCallingUid();
1273
1274    // verify id is valid.
1275    auto state = getCameraState(id);
1276    if (state == nullptr) {
1277        ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1278        return -EINVAL;
1279    }
1280
1281    ICameraServiceListener::Status cameraStatus = state->getStatus();
1282    if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1283            cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1284        ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1285        return -EINVAL;
1286    }
1287
1288    {
1289        Mutex::Autolock al(mTorchStatusMutex);
1290        ICameraServiceListener::TorchStatus status;
1291        status_t res = getTorchStatusLocked(id, &status);
1292        if (res) {
1293            ALOGE("%s: getting current torch status failed for camera %s",
1294                    __FUNCTION__, id.string());
1295            return -EINVAL;
1296        }
1297
1298        if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
1299            if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1300                ALOGE("%s: torch mode of camera %s is not available because "
1301                        "camera is in use", __FUNCTION__, id.string());
1302                return -EBUSY;
1303            } else {
1304                ALOGE("%s: torch mode of camera %s is not available due to "
1305                        "insufficient resources", __FUNCTION__, id.string());
1306                return -EUSERS;
1307            }
1308        }
1309    }
1310
1311    {
1312        // Update UID map - this is used in the torch status changed callbacks, so must be done
1313        // before setTorchMode
1314        Mutex::Autolock al(mTorchUidMapMutex);
1315        if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1316            mTorchUidMap[id].first = uid;
1317            mTorchUidMap[id].second = uid;
1318        } else {
1319            // Set the pending UID
1320            mTorchUidMap[id].first = uid;
1321        }
1322    }
1323
1324    status_t res = mFlashlight->setTorchMode(id, enabled);
1325
1326    if (res) {
1327        ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1328                __FUNCTION__, id.string(), enabled, strerror(-res), res);
1329        return res;
1330    }
1331
1332    {
1333        // update the link to client's death
1334        Mutex::Autolock al(mTorchClientMapMutex);
1335        ssize_t index = mTorchClientMap.indexOfKey(id);
1336        if (enabled) {
1337            if (index == NAME_NOT_FOUND) {
1338                mTorchClientMap.add(id, clientBinder);
1339            } else {
1340                mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1341                mTorchClientMap.replaceValueAt(index, clientBinder);
1342            }
1343            clientBinder->linkToDeath(this);
1344        } else if (index != NAME_NOT_FOUND) {
1345            mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1346        }
1347    }
1348
1349    return OK;
1350}
1351
1352void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
1353    ATRACE_CALL();
1354
1355    switch(eventId) {
1356        case ICameraService::USER_SWITCHED: {
1357            doUserSwitch(/*newUserIds*/args, /*length*/length);
1358            break;
1359        }
1360        case ICameraService::NO_EVENT:
1361        default: {
1362            ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1363                    eventId);
1364            break;
1365        }
1366    }
1367}
1368
1369status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
1370    ATRACE_CALL();
1371
1372    ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1373
1374    if (listener == nullptr) {
1375        ALOGE("%s: Listener must not be null", __FUNCTION__);
1376        return BAD_VALUE;
1377    }
1378
1379    Mutex::Autolock lock(mServiceLock);
1380
1381    {
1382        Mutex::Autolock lock(mStatusListenerLock);
1383        for (auto& it : mListenerList) {
1384            if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1385                ALOGW("%s: Tried to add listener %p which was already subscribed",
1386                      __FUNCTION__, listener.get());
1387                return ALREADY_EXISTS;
1388            }
1389        }
1390
1391        mListenerList.push_back(listener);
1392    }
1393
1394
1395    /* Immediately signal current status to this listener only */
1396    {
1397        Mutex::Autolock lock(mCameraStatesLock);
1398        for (auto& i : mCameraStates) {
1399            // TODO: Update binder to use String16 for camera IDs and remove;
1400            int id = cameraIdToInt(i.first);
1401            if (id == -1) continue;
1402
1403            listener->onStatusChanged(i.second->getStatus(), id);
1404        }
1405    }
1406
1407    /* Immediately signal current torch status to this listener only */
1408    {
1409        Mutex::Autolock al(mTorchStatusMutex);
1410        for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
1411            String16 id = String16(mTorchStatusMap.keyAt(i).string());
1412            listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
1413        }
1414    }
1415
1416    return OK;
1417}
1418
1419status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1420    ATRACE_CALL();
1421
1422    ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1423
1424    if (listener == 0) {
1425        ALOGE("%s: Listener must not be null", __FUNCTION__);
1426        return BAD_VALUE;
1427    }
1428
1429    Mutex::Autolock lock(mServiceLock);
1430
1431    {
1432        Mutex::Autolock lock(mStatusListenerLock);
1433        for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1434            if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1435                mListenerList.erase(it);
1436                return OK;
1437            }
1438        }
1439    }
1440
1441    ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1442          __FUNCTION__, listener.get());
1443
1444    return BAD_VALUE;
1445}
1446
1447status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1448
1449    ATRACE_CALL();
1450    ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1451
1452    if (parameters == NULL) {
1453        ALOGE("%s: parameters must not be null", __FUNCTION__);
1454        return BAD_VALUE;
1455    }
1456
1457    status_t ret = 0;
1458
1459    CameraParameters shimParams;
1460    if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1461        // Error logged by caller
1462        return ret;
1463    }
1464
1465    String8 shimParamsString8 = shimParams.flatten();
1466    String16 shimParamsString16 = String16(shimParamsString8);
1467
1468    *parameters = shimParamsString16;
1469
1470    return OK;
1471}
1472
1473status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1474    ATRACE_CALL();
1475
1476    ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1477
1478    switch (apiVersion) {
1479        case API_VERSION_1:
1480        case API_VERSION_2:
1481            break;
1482        default:
1483            ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1484            return BAD_VALUE;
1485    }
1486
1487    int facing = -1;
1488    int deviceVersion = getDeviceVersion(cameraId, &facing);
1489
1490    switch(deviceVersion) {
1491      case CAMERA_DEVICE_API_VERSION_1_0:
1492      case CAMERA_DEVICE_API_VERSION_3_0:
1493      case CAMERA_DEVICE_API_VERSION_3_1:
1494        if (apiVersion == API_VERSION_2) {
1495            ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1496                    __FUNCTION__, cameraId);
1497            return -EOPNOTSUPP;
1498        } else { // if (apiVersion == API_VERSION_1) {
1499            ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1500                    __FUNCTION__, cameraId);
1501            return OK;
1502        }
1503      case CAMERA_DEVICE_API_VERSION_3_2:
1504      case CAMERA_DEVICE_API_VERSION_3_3:
1505        ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1506                __FUNCTION__, cameraId);
1507        return OK;
1508      case -1:
1509        ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1510        return BAD_VALUE;
1511      default:
1512        ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1513        return INVALID_OPERATION;
1514    }
1515
1516    return OK;
1517}
1518
1519void CameraService::removeByClient(const BasicClient* client) {
1520    Mutex::Autolock lock(mServiceLock);
1521    for (auto& i : mActiveClientManager.getAll()) {
1522        auto clientSp = i->getValue();
1523        if (clientSp.get() == client) {
1524            mActiveClientManager.remove(i);
1525        }
1526    }
1527}
1528
1529bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1530    const int callingPid = getCallingPid();
1531    const int servicePid = getpid();
1532    bool ret = false;
1533    {
1534        // Acquire mServiceLock and prevent other clients from connecting
1535        std::unique_ptr<AutoConditionLock> lock =
1536                AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1537
1538
1539        std::vector<sp<BasicClient>> evicted;
1540        for (auto& i : mActiveClientManager.getAll()) {
1541            auto clientSp = i->getValue();
1542            if (clientSp.get() == nullptr) {
1543                ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1544                mActiveClientManager.remove(i);
1545                continue;
1546            }
1547            if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1548                    callingPid == clientSp->getClientPid())) {
1549                mActiveClientManager.remove(i);
1550                evicted.push_back(clientSp);
1551
1552                // Notify the client of disconnection
1553                clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1554                        CaptureResultExtras());
1555            }
1556        }
1557
1558        // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1559        // other clients from connecting in mServiceLockWrapper if held
1560        mServiceLock.unlock();
1561
1562        // Do not clear caller identity, remote caller should be client proccess
1563
1564        for (auto& i : evicted) {
1565            if (i.get() != nullptr) {
1566                i->disconnect();
1567                ret = true;
1568            }
1569        }
1570
1571        // Reacquire mServiceLock
1572        mServiceLock.lock();
1573
1574    } // lock is destroyed, allow further connect calls
1575
1576    return ret;
1577}
1578
1579
1580/**
1581 * Check camera capabilities, such as support for basic color operation
1582 * Also check that the device HAL version is still in support
1583 */
1584int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1585    // device_version undefined in CAMERA_MODULE_API_VERSION_1_0,
1586    // All CAMERA_MODULE_API_VERSION_1_0 devices are backward-compatible
1587    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0) {
1588        // Verify the device version is in the supported range
1589        switch (info.device_version) {
1590            case CAMERA_DEVICE_API_VERSION_1_0:
1591            case CAMERA_DEVICE_API_VERSION_3_0:
1592            case CAMERA_DEVICE_API_VERSION_3_1:
1593            case CAMERA_DEVICE_API_VERSION_3_2:
1594            case CAMERA_DEVICE_API_VERSION_3_3:
1595                // in support
1596                break;
1597            case CAMERA_DEVICE_API_VERSION_2_0:
1598            case CAMERA_DEVICE_API_VERSION_2_1:
1599                // no longer supported
1600            default:
1601                ALOGE("%s: Device %d has HAL version %x, which is not supported",
1602                        __FUNCTION__, id, info.device_version);
1603                String8 msg = String8::format(
1604                        "Unsupported device HAL version %x for device %d",
1605                        info.device_version, id);
1606                logServiceError(msg.string(), NO_INIT);
1607                return NO_INIT;
1608        }
1609    }
1610
1611    // Assume all devices pre-v3.3 are backward-compatible
1612    bool isBackwardCompatible = true;
1613    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1614            && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1615        isBackwardCompatible = false;
1616        status_t res;
1617        camera_metadata_ro_entry_t caps;
1618        res = find_camera_metadata_ro_entry(
1619            info.static_camera_characteristics,
1620            ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1621            &caps);
1622        if (res != 0) {
1623            ALOGW("%s: Unable to find camera capabilities for camera device %d",
1624                    __FUNCTION__, id);
1625            caps.count = 0;
1626        }
1627        for (size_t i = 0; i < caps.count; i++) {
1628            if (caps.data.u8[i] ==
1629                    ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1630                isBackwardCompatible = true;
1631                break;
1632            }
1633        }
1634    }
1635
1636    if (!isBackwardCompatible) {
1637        mNumberOfNormalCameras--;
1638        *latestStrangeCameraId = id;
1639    } else {
1640        if (id > *latestStrangeCameraId) {
1641            ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1642                    "This is not allowed due backward-compatibility requirements",
1643                    __FUNCTION__, id, *latestStrangeCameraId);
1644            logServiceError("Invalid order of camera devices", NO_INIT);
1645            mNumberOfCameras = 0;
1646            mNumberOfNormalCameras = 0;
1647            return NO_INIT;
1648        }
1649    }
1650    return OK;
1651}
1652
1653std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1654        const String8& cameraId) const {
1655    std::shared_ptr<CameraState> state;
1656    {
1657        Mutex::Autolock lock(mCameraStatesLock);
1658        auto iter = mCameraStates.find(cameraId);
1659        if (iter != mCameraStates.end()) {
1660            state = iter->second;
1661        }
1662    }
1663    return state;
1664}
1665
1666sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1667    // Remove from active clients list
1668    auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1669    if (clientDescriptorPtr == nullptr) {
1670        ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1671                cameraId.string());
1672        return sp<BasicClient>{nullptr};
1673    }
1674
1675    return clientDescriptorPtr->getValue();
1676}
1677
1678void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
1679    // Acquire mServiceLock and prevent other clients from connecting
1680    std::unique_ptr<AutoConditionLock> lock =
1681            AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1682
1683    std::set<userid_t> newAllowedUsers;
1684    for (size_t i = 0; i < length; i++) {
1685        if (newUserId[i] < 0) {
1686            ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1687                    __FUNCTION__, newUserId[i]);
1688            return;
1689        }
1690        newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
1691    }
1692
1693
1694    if (newAllowedUsers == mAllowedUsers) {
1695        ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1696        return;
1697    }
1698
1699    logUserSwitch(mAllowedUsers, newAllowedUsers);
1700
1701    mAllowedUsers = std::move(newAllowedUsers);
1702
1703    // Current user has switched, evict all current clients.
1704    std::vector<sp<BasicClient>> evicted;
1705    for (auto& i : mActiveClientManager.getAll()) {
1706        auto clientSp = i->getValue();
1707
1708        if (clientSp.get() == nullptr) {
1709            ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1710            continue;
1711        }
1712
1713        // Don't evict clients that are still allowed.
1714        uid_t clientUid = clientSp->getClientUid();
1715        userid_t clientUserId = multiuser_get_user_id(clientUid);
1716        if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1717            continue;
1718        }
1719
1720        evicted.push_back(clientSp);
1721
1722        String8 curTime = getFormattedCurrentTime();
1723
1724        ALOGE("Evicting conflicting client for camera ID %s due to user change",
1725                i->getKey().string());
1726
1727        // Log the clients evicted
1728        logEvent(String8::format("EVICT device %s client held by package %s (PID %"
1729                PRId32 ", priority %" PRId32 ")\n   - Evicted due to user switch.",
1730                i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1731                i->getOwnerId(), i->getPriority()));
1732
1733    }
1734
1735    // Do not hold mServiceLock while disconnecting clients, but retain the condition
1736    // blocking other clients from connecting in mServiceLockWrapper if held.
1737    mServiceLock.unlock();
1738
1739    // Clear caller identity temporarily so client disconnect PID checks work correctly
1740    int64_t token = IPCThreadState::self()->clearCallingIdentity();
1741
1742    for (auto& i : evicted) {
1743        i->disconnect();
1744    }
1745
1746    IPCThreadState::self()->restoreCallingIdentity(token);
1747
1748    // Reacquire mServiceLock
1749    mServiceLock.lock();
1750}
1751
1752void CameraService::logEvent(const char* event) {
1753    String8 curTime = getFormattedCurrentTime();
1754    Mutex::Autolock l(mLogLock);
1755    mEventLog.add(String8::format("%s : %s", curTime.string(), event));
1756}
1757
1758void CameraService::logDisconnected(const char* cameraId, int clientPid,
1759        const char* clientPackage) {
1760    // Log the clients evicted
1761    logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1762            clientPackage, clientPid));
1763}
1764
1765void CameraService::logConnected(const char* cameraId, int clientPid,
1766        const char* clientPackage) {
1767    // Log the clients evicted
1768    logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1769            clientPackage, clientPid));
1770}
1771
1772void CameraService::logRejected(const char* cameraId, int clientPid,
1773        const char* clientPackage, const char* reason) {
1774    // Log the client rejected
1775    logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1776            cameraId, clientPackage, clientPid, reason));
1777}
1778
1779void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1780        const std::set<userid_t>& newUserIds) {
1781    String8 newUsers = toString(newUserIds);
1782    String8 oldUsers = toString(oldUserIds);
1783    // Log the new and old users
1784    logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1785            oldUsers.string(), newUsers.string()));
1786}
1787
1788void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1789    // Log the device removal
1790    logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1791}
1792
1793void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1794    // Log the device removal
1795    logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1796}
1797
1798void CameraService::logClientDied(int clientPid, const char* reason) {
1799    // Log the device removal
1800    logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
1801}
1802
1803void CameraService::logServiceError(const char* msg, int errorCode) {
1804    String8 curTime = getFormattedCurrentTime();
1805    logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(-errorCode)));
1806}
1807
1808status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1809        uint32_t flags) {
1810
1811    const int pid = getCallingPid();
1812    const int selfPid = getpid();
1813
1814    // Permission checks
1815    switch (code) {
1816        case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1817            if (pid != selfPid) {
1818                // Ensure we're being called by system_server, or similar process with
1819                // permissions to notify the camera service about system events
1820                if (!checkCallingPermission(
1821                        String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1822                    const int uid = getCallingUid();
1823                    ALOGE("Permission Denial: cannot send updates to camera service about system"
1824                            " events from pid=%d, uid=%d", pid, uid);
1825                    return PERMISSION_DENIED;
1826                }
1827            }
1828            break;
1829        }
1830    }
1831
1832    return BnCameraService::onTransact(code, data, reply, flags);
1833}
1834
1835// We share the media players for shutter and recording sound for all clients.
1836// A reference count is kept to determine when we will actually release the
1837// media players.
1838
1839MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1840    MediaPlayer* mp = new MediaPlayer();
1841    if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1842        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1843        mp->prepare();
1844    } else {
1845        ALOGE("Failed to load CameraService sounds: %s", file);
1846        return NULL;
1847    }
1848    return mp;
1849}
1850
1851void CameraService::loadSound() {
1852    ATRACE_CALL();
1853
1854    Mutex::Autolock lock(mSoundLock);
1855    LOG1("CameraService::loadSound ref=%d", mSoundRef);
1856    if (mSoundRef++) return;
1857
1858    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1859    mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1860    mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
1861}
1862
1863void CameraService::releaseSound() {
1864    Mutex::Autolock lock(mSoundLock);
1865    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1866    if (--mSoundRef) return;
1867
1868    for (int i = 0; i < NUM_SOUNDS; i++) {
1869        if (mSoundPlayer[i] != 0) {
1870            mSoundPlayer[i]->disconnect();
1871            mSoundPlayer[i].clear();
1872        }
1873    }
1874}
1875
1876void CameraService::playSound(sound_kind kind) {
1877    ATRACE_CALL();
1878
1879    LOG1("playSound(%d)", kind);
1880    Mutex::Autolock lock(mSoundLock);
1881    sp<MediaPlayer> player = mSoundPlayer[kind];
1882    if (player != 0) {
1883        player->seekTo(0);
1884        player->start();
1885    }
1886}
1887
1888// ----------------------------------------------------------------------------
1889
1890CameraService::Client::Client(const sp<CameraService>& cameraService,
1891        const sp<ICameraClient>& cameraClient,
1892        const String16& clientPackageName,
1893        int cameraId, int cameraFacing,
1894        int clientPid, uid_t clientUid,
1895        int servicePid) :
1896        CameraService::BasicClient(cameraService,
1897                IInterface::asBinder(cameraClient),
1898                clientPackageName,
1899                cameraId, cameraFacing,
1900                clientPid, clientUid,
1901                servicePid)
1902{
1903    int callingPid = getCallingPid();
1904    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1905
1906    mRemoteCallback = cameraClient;
1907
1908    cameraService->loadSound();
1909
1910    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1911}
1912
1913// tear down the client
1914CameraService::Client::~Client() {
1915    ALOGV("~Client");
1916    mDestructionStarted = true;
1917
1918    mCameraService->releaseSound();
1919    // unconditionally disconnect. function is idempotent
1920    Client::disconnect();
1921}
1922
1923CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1924        const sp<IBinder>& remoteCallback,
1925        const String16& clientPackageName,
1926        int cameraId, int cameraFacing,
1927        int clientPid, uid_t clientUid,
1928        int servicePid):
1929        mClientPackageName(clientPackageName), mDisconnected(false)
1930{
1931    mCameraService = cameraService;
1932    mRemoteBinder = remoteCallback;
1933    mCameraId = cameraId;
1934    mCameraFacing = cameraFacing;
1935    mClientPid = clientPid;
1936    mClientUid = clientUid;
1937    mServicePid = servicePid;
1938    mOpsActive = false;
1939    mDestructionStarted = false;
1940}
1941
1942CameraService::BasicClient::~BasicClient() {
1943    ALOGV("~BasicClient");
1944    mDestructionStarted = true;
1945}
1946
1947void CameraService::BasicClient::disconnect() {
1948    if (mDisconnected) {
1949        return;
1950    }
1951    mDisconnected = true;
1952
1953    mCameraService->removeByClient(this);
1954    mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1955            String8(mClientPackageName));
1956
1957    sp<IBinder> remote = getRemote();
1958    if (remote != nullptr) {
1959        remote->unlinkToDeath(mCameraService);
1960    }
1961
1962    finishCameraOps();
1963    ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1964
1965    // client shouldn't be able to call into us anymore
1966    mClientPid = 0;
1967}
1968
1969status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
1970    // No dumping of clients directly over Binder,
1971    // must go through CameraService::dump
1972    android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
1973            IPCThreadState::self()->getCallingUid(), NULL, 0);
1974    return OK;
1975}
1976
1977String16 CameraService::BasicClient::getPackageName() const {
1978    return mClientPackageName;
1979}
1980
1981
1982int CameraService::BasicClient::getClientPid() const {
1983    return mClientPid;
1984}
1985
1986uid_t CameraService::BasicClient::getClientUid() const {
1987    return mClientUid;
1988}
1989
1990bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1991    // Defaults to API2.
1992    return level == API_2;
1993}
1994
1995status_t CameraService::BasicClient::startCameraOps() {
1996    ATRACE_CALL();
1997
1998    int32_t res;
1999    // Notify app ops that the camera is not available
2000    mOpsCallback = new OpsCallback(this);
2001
2002    {
2003        ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
2004              __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
2005    }
2006
2007    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
2008            mClientPackageName, mOpsCallback);
2009    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
2010            mClientUid, mClientPackageName);
2011
2012    if (res == AppOpsManager::MODE_ERRORED) {
2013        ALOGI("Camera %d: Access for \"%s\" has been revoked",
2014                mCameraId, String8(mClientPackageName).string());
2015        return PERMISSION_DENIED;
2016    }
2017
2018    if (res == AppOpsManager::MODE_IGNORED) {
2019        ALOGI("Camera %d: Access for \"%s\" has been restricted",
2020                mCameraId, String8(mClientPackageName).string());
2021        // Return the same error as for device policy manager rejection
2022        return -EACCES;
2023    }
2024
2025    mOpsActive = true;
2026
2027    // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
2028    mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
2029            String8::format("%d", mCameraId));
2030
2031    // Transition device state to OPEN
2032    mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2033            String8::format("%d", mCameraId));
2034
2035    return OK;
2036}
2037
2038status_t CameraService::BasicClient::finishCameraOps() {
2039    ATRACE_CALL();
2040
2041    // Check if startCameraOps succeeded, and if so, finish the camera op
2042    if (mOpsActive) {
2043        // Notify app ops that the camera is available again
2044        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2045                mClientPackageName);
2046        mOpsActive = false;
2047
2048        auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2049                ICameraServiceListener::STATUS_ENUMERATING};
2050
2051        // Transition to PRESENT if the camera is not in either of the rejected states
2052        mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
2053                String8::format("%d", mCameraId), rejected);
2054
2055        // Transition device state to CLOSED
2056        mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2057                String8::format("%d", mCameraId));
2058
2059        // Notify flashlight that a camera device is closed.
2060        mCameraService->mFlashlight->deviceClosed(
2061                String8::format("%d", mCameraId));
2062    }
2063    // Always stop watching, even if no camera op is active
2064    if (mOpsCallback != NULL) {
2065        mAppOpsManager.stopWatchingMode(mOpsCallback);
2066    }
2067    mOpsCallback.clear();
2068
2069    return OK;
2070}
2071
2072void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
2073    ATRACE_CALL();
2074
2075    String8 name(packageName);
2076    String8 myName(mClientPackageName);
2077
2078    if (op != AppOpsManager::OP_CAMERA) {
2079        ALOGW("Unexpected app ops notification received: %d", op);
2080        return;
2081    }
2082
2083    int32_t res;
2084    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
2085            mClientUid, mClientPackageName);
2086    ALOGV("checkOp returns: %d, %s ", res,
2087            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2088            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2089            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2090            "UNKNOWN");
2091
2092    if (res != AppOpsManager::MODE_ALLOWED) {
2093        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2094                myName.string());
2095        // Reset the client PID to allow server-initiated disconnect,
2096        // and to prevent further calls by client.
2097        mClientPid = getCallingPid();
2098        CaptureResultExtras resultExtras; // a dummy result (invalid)
2099        notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
2100        disconnect();
2101    }
2102}
2103
2104// ----------------------------------------------------------------------------
2105
2106// Provide client strong pointer for callbacks.
2107sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2108    String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2109    auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2110    if (clientDescriptor != nullptr) {
2111        return sp<Client>{
2112                static_cast<Client*>(clientDescriptor->getValue().get())};
2113    }
2114    return sp<Client>{nullptr};
2115}
2116
2117void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2118        const CaptureResultExtras& resultExtras) {
2119    (void) errorCode;
2120    (void) resultExtras;
2121    if (mRemoteCallback != NULL) {
2122        mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2123    } else {
2124        ALOGE("mRemoteCallback is NULL!!");
2125    }
2126}
2127
2128// NOTE: function is idempotent
2129void CameraService::Client::disconnect() {
2130    ALOGV("Client::disconnect");
2131    BasicClient::disconnect();
2132}
2133
2134bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2135    return level == API_1;
2136}
2137
2138CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2139        mClient(client) {
2140}
2141
2142void CameraService::Client::OpsCallback::opChanged(int32_t op,
2143        const String16& packageName) {
2144    sp<BasicClient> client = mClient.promote();
2145    if (client != NULL) {
2146        client->opChanged(op, packageName);
2147    }
2148}
2149
2150// ----------------------------------------------------------------------------
2151//                  CameraState
2152// ----------------------------------------------------------------------------
2153
2154CameraService::CameraState::CameraState(const String8& id, int cost,
2155        const std::set<String8>& conflicting) : mId(id),
2156        mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2157
2158CameraService::CameraState::~CameraState() {}
2159
2160ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2161    Mutex::Autolock lock(mStatusLock);
2162    return mStatus;
2163}
2164
2165CameraParameters CameraService::CameraState::getShimParams() const {
2166    return mShimParams;
2167}
2168
2169void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2170    mShimParams = params;
2171}
2172
2173int CameraService::CameraState::getCost() const {
2174    return mCost;
2175}
2176
2177std::set<String8> CameraService::CameraState::getConflicting() const {
2178    return mConflicting;
2179}
2180
2181String8 CameraService::CameraState::getId() const {
2182    return mId;
2183}
2184
2185// ----------------------------------------------------------------------------
2186//                  ClientEventListener
2187// ----------------------------------------------------------------------------
2188
2189void CameraService::ClientEventListener::onClientAdded(
2190        const resource_policy::ClientDescriptor<String8,
2191        sp<CameraService::BasicClient>>& descriptor) {
2192    auto basicClient = descriptor.getValue();
2193    if (basicClient.get() != nullptr) {
2194        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2195        notifier.noteStartCamera(descriptor.getKey(),
2196                static_cast<int>(basicClient->getClientUid()));
2197    }
2198}
2199
2200void CameraService::ClientEventListener::onClientRemoved(
2201        const resource_policy::ClientDescriptor<String8,
2202        sp<CameraService::BasicClient>>& descriptor) {
2203    auto basicClient = descriptor.getValue();
2204    if (basicClient.get() != nullptr) {
2205        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2206        notifier.noteStopCamera(descriptor.getKey(),
2207                static_cast<int>(basicClient->getClientUid()));
2208    }
2209}
2210
2211
2212// ----------------------------------------------------------------------------
2213//                  CameraClientManager
2214// ----------------------------------------------------------------------------
2215
2216CameraService::CameraClientManager::CameraClientManager() {
2217    setListener(std::make_shared<ClientEventListener>());
2218}
2219
2220CameraService::CameraClientManager::~CameraClientManager() {}
2221
2222sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2223        const String8& id) const {
2224    auto descriptor = get(id);
2225    if (descriptor == nullptr) {
2226        return sp<BasicClient>{nullptr};
2227    }
2228    return descriptor->getValue();
2229}
2230
2231String8 CameraService::CameraClientManager::toString() const {
2232    auto all = getAll();
2233    String8 ret("[");
2234    bool hasAny = false;
2235    for (auto& i : all) {
2236        hasAny = true;
2237        String8 key = i->getKey();
2238        int32_t cost = i->getCost();
2239        int32_t pid = i->getOwnerId();
2240        int32_t priority = i->getPriority();
2241        auto conflicting = i->getConflicting();
2242        auto clientSp = i->getValue();
2243        String8 packageName;
2244        userid_t clientUserId = 0;
2245        if (clientSp.get() != nullptr) {
2246            packageName = String8{clientSp->getPackageName()};
2247            uid_t clientUid = clientSp->getClientUid();
2248            clientUserId = multiuser_get_user_id(clientUid);
2249        }
2250        ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2251                PRId32 ", ", key.string(), cost, pid, priority);
2252
2253        if (clientSp.get() != nullptr) {
2254            ret.appendFormat("User Id: %d, ", clientUserId);
2255        }
2256        if (packageName.size() != 0) {
2257            ret.appendFormat("Client Package Name: %s", packageName.string());
2258        }
2259
2260        ret.append(", Conflicting Client Devices: {");
2261        for (auto& j : conflicting) {
2262            ret.appendFormat("%s, ", j.string());
2263        }
2264        ret.append("})");
2265    }
2266    if (hasAny) ret.append("\n");
2267    ret.append("]\n");
2268    return ret;
2269}
2270
2271CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2272        const String8& key, const sp<BasicClient>& value, int32_t cost,
2273        const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2274
2275    return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2276            key, value, cost, conflictingKeys, priority, ownerId);
2277}
2278
2279CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2280        const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2281    return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2282            partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2283}
2284
2285// ----------------------------------------------------------------------------
2286
2287static const int kDumpLockRetries = 50;
2288static const int kDumpLockSleep = 60000;
2289
2290static bool tryLock(Mutex& mutex)
2291{
2292    bool locked = false;
2293    for (int i = 0; i < kDumpLockRetries; ++i) {
2294        if (mutex.tryLock() == NO_ERROR) {
2295            locked = true;
2296            break;
2297        }
2298        usleep(kDumpLockSleep);
2299    }
2300    return locked;
2301}
2302
2303status_t CameraService::dump(int fd, const Vector<String16>& args) {
2304    ATRACE_CALL();
2305
2306    String8 result("Dump of the Camera Service:\n");
2307    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
2308        result = result.format("Permission Denial: "
2309                "can't dump CameraService from pid=%d, uid=%d\n",
2310                getCallingPid(),
2311                getCallingUid());
2312        write(fd, result.string(), result.size());
2313    } else {
2314        bool locked = tryLock(mServiceLock);
2315        // failed to lock - CameraService is probably deadlocked
2316        if (!locked) {
2317            result.append("CameraService may be deadlocked\n");
2318            write(fd, result.string(), result.size());
2319        }
2320
2321        bool hasClient = false;
2322        if (!mModule) {
2323            result = String8::format("No camera module available!\n");
2324            write(fd, result.string(), result.size());
2325
2326            // Dump event log for error information
2327            dumpEventLog(fd);
2328
2329            if (locked) mServiceLock.unlock();
2330            return NO_ERROR;
2331        }
2332
2333        result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2334        result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2335        result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2336        result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
2337        result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2338        result.appendFormat("Number of normal camera devices: %d\n", mNumberOfNormalCameras);
2339        String8 activeClientString = mActiveClientManager.toString();
2340        result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2341        result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
2342
2343        sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2344        if (desc == NULL) {
2345            result.appendFormat("Vendor tags left unimplemented.\n");
2346        } else {
2347            result.appendFormat("Vendor tag definitions:\n");
2348        }
2349
2350        write(fd, result.string(), result.size());
2351
2352        if (desc != NULL) {
2353            desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2354        }
2355
2356        dumpEventLog(fd);
2357
2358        bool stateLocked = tryLock(mCameraStatesLock);
2359        if (!stateLocked) {
2360            result = String8::format("CameraStates in use, may be deadlocked\n");
2361            write(fd, result.string(), result.size());
2362        }
2363
2364        for (auto& state : mCameraStates) {
2365            String8 cameraId = state.first;
2366            result = String8::format("Camera %s information:\n", cameraId.string());
2367            camera_info info;
2368
2369            // TODO: Change getCameraInfo + HAL to use String cameraIds
2370            status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
2371            if (rc != OK) {
2372                result.appendFormat("  Error reading static information!\n");
2373                write(fd, result.string(), result.size());
2374            } else {
2375                result.appendFormat("  Facing: %s\n",
2376                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2377                result.appendFormat("  Orientation: %d\n", info.orientation);
2378                int deviceVersion;
2379                if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
2380                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2381                } else {
2382                    deviceVersion = info.device_version;
2383                }
2384
2385                auto conflicting = state.second->getConflicting();
2386                result.appendFormat("  Resource Cost: %d\n", state.second->getCost());
2387                result.appendFormat("  Conflicting Devices:");
2388                for (auto& id : conflicting) {
2389                    result.appendFormat(" %s", id.string());
2390                }
2391                if (conflicting.size() == 0) {
2392                    result.appendFormat(" NONE");
2393                }
2394                result.appendFormat("\n");
2395
2396                result.appendFormat("  Device version: %#x\n", deviceVersion);
2397                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_3_0) {
2398                    result.appendFormat("  Device static metadata:\n");
2399                    write(fd, result.string(), result.size());
2400                    dump_indented_camera_metadata(info.static_camera_characteristics,
2401                            fd, /*verbosity*/2, /*indentation*/4);
2402                } else {
2403                    write(fd, result.string(), result.size());
2404                }
2405
2406                CameraParameters p = state.second->getShimParams();
2407                if (!p.isEmpty()) {
2408                    result = String8::format("  Camera1 API shim is using parameters:\n        ");
2409                    write(fd, result.string(), result.size());
2410                    p.dump(fd, args);
2411                }
2412            }
2413
2414            auto clientDescriptor = mActiveClientManager.get(cameraId);
2415            if (clientDescriptor == nullptr) {
2416                result = String8::format("  Device %s is closed, no client instance\n",
2417                        cameraId.string());
2418                write(fd, result.string(), result.size());
2419                continue;
2420            }
2421            hasClient = true;
2422            result = String8::format("  Device %s is open. Client instance dump:\n\n",
2423                    cameraId.string());
2424            result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2425            result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2426
2427            auto client = clientDescriptor->getValue();
2428            result.appendFormat("Client package: %s\n",
2429                    String8(client->getPackageName()).string());
2430            write(fd, result.string(), result.size());
2431
2432            client->dumpClient(fd, args);
2433        }
2434
2435        if (stateLocked) mCameraStatesLock.unlock();
2436
2437        if (!hasClient) {
2438            result = String8::format("\nNo active camera clients yet.\n");
2439            write(fd, result.string(), result.size());
2440        }
2441
2442        if (locked) mServiceLock.unlock();
2443
2444        // Dump camera traces if there were any
2445        write(fd, "\n", 1);
2446        camera3::CameraTraces::dump(fd, args);
2447
2448        // change logging level
2449        int n = args.size();
2450        for (int i = 0; i + 1 < n; i++) {
2451            String16 verboseOption("-v");
2452            if (args[i] == verboseOption) {
2453                String8 levelStr(args[i+1]);
2454                int level = atoi(levelStr.string());
2455                result = String8::format("\nSetting log level to %d.\n", level);
2456                setLogLevel(level);
2457                write(fd, result.string(), result.size());
2458            }
2459        }
2460    }
2461    return NO_ERROR;
2462}
2463
2464void CameraService::dumpEventLog(int fd) {
2465    String8 result = String8("\nPrior client events (most recent at top):\n");
2466
2467    Mutex::Autolock l(mLogLock);
2468    for (const auto& msg : mEventLog) {
2469        result.appendFormat("  %s\n", msg.string());
2470    }
2471
2472    if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2473        result.append("  ...\n");
2474    } else if (mEventLog.size() == 0) {
2475        result.append("  [no events yet]\n");
2476    }
2477    result.append("\n");
2478
2479    write(fd, result.string(), result.size());
2480}
2481
2482void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
2483    Mutex::Autolock al(mTorchClientMapMutex);
2484    for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2485        if (mTorchClientMap[i] == who) {
2486            // turn off the torch mode that was turned on by dead client
2487            String8 cameraId = mTorchClientMap.keyAt(i);
2488            status_t res = mFlashlight->setTorchMode(cameraId, false);
2489            if (res) {
2490                ALOGE("%s: torch client died but couldn't turn off torch: "
2491                    "%s (%d)", __FUNCTION__, strerror(-res), res);
2492                return;
2493            }
2494            mTorchClientMap.removeItemsAt(i);
2495            break;
2496        }
2497    }
2498}
2499
2500/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
2501
2502    /**
2503      * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2504      * binder driver
2505      */
2506
2507    logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2508
2509    // check torch client
2510    handleTorchClientBinderDied(who);
2511
2512    // check camera device client
2513    if(!evictClientIdByRemote(who)) {
2514        ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
2515        return;
2516    }
2517
2518    ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2519            __FUNCTION__);
2520}
2521
2522void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2523    updateStatus(status, cameraId, {});
2524}
2525
2526void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2527        std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2528    // Do not lock mServiceLock here or can get into a deadlock from
2529    // connect() -> disconnect -> updateStatus
2530
2531    auto state = getCameraState(cameraId);
2532
2533    if (state == nullptr) {
2534        ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2535                cameraId.string());
2536        return;
2537    }
2538
2539    // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2540    // of the listeners with both the mStatusStatus and mStatusListenerLock held
2541    state->updateStatus(status, cameraId, rejectSourceStates, [this]
2542            (const String8& cameraId, ICameraServiceListener::Status status) {
2543
2544            if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2545                // Update torch status if it has a flash unit.
2546                Mutex::Autolock al(mTorchStatusMutex);
2547                ICameraServiceListener::TorchStatus torchStatus;
2548                if (getTorchStatusLocked(cameraId, &torchStatus) !=
2549                        NAME_NOT_FOUND) {
2550                    ICameraServiceListener::TorchStatus newTorchStatus =
2551                            status == ICameraServiceListener::STATUS_PRESENT ?
2552                            ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2553                            ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2554                    if (torchStatus != newTorchStatus) {
2555                        onTorchStatusChangedLocked(cameraId, newTorchStatus);
2556                    }
2557                }
2558            }
2559
2560            Mutex::Autolock lock(mStatusListenerLock);
2561
2562            for (auto& listener : mListenerList) {
2563                // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2564                int id = cameraIdToInt(cameraId);
2565                if (id != -1) listener->onStatusChanged(status, id);
2566            }
2567        });
2568}
2569
2570void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2571        const String8& cameraId) {
2572    sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2573    if (proxyBinder == nullptr) return;
2574    String16 id(cameraId);
2575    proxyBinder->notifyCameraState(id, newState);
2576}
2577
2578status_t CameraService::getTorchStatusLocked(
2579        const String8& cameraId,
2580        ICameraServiceListener::TorchStatus *status) const {
2581    if (!status) {
2582        return BAD_VALUE;
2583    }
2584    ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2585    if (index == NAME_NOT_FOUND) {
2586        // invalid camera ID or the camera doesn't have a flash unit
2587        return NAME_NOT_FOUND;
2588    }
2589
2590    *status = mTorchStatusMap.valueAt(index);
2591    return OK;
2592}
2593
2594status_t CameraService::setTorchStatusLocked(const String8& cameraId,
2595        ICameraServiceListener::TorchStatus status) {
2596    ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2597    if (index == NAME_NOT_FOUND) {
2598        return BAD_VALUE;
2599    }
2600    ICameraServiceListener::TorchStatus& item =
2601            mTorchStatusMap.editValueAt(index);
2602    item = status;
2603
2604    return OK;
2605}
2606
2607}; // namespace android
2608