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