CameraService.cpp revision 6dd6c546513aa18dc1d7fba0f72d670edce34f77
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 (clientUid == USE_CALLING_UID) {
869        clientUid = getCallingUid();
870    } else {
871        // We only trust our own process to forward client UIDs
872        if (callingPid != getpid()) {
873            ALOGE("CameraService::connect X (PID %d) rejected (don't trust clientUid %d)",
874                    callingPid, clientUid);
875            return PERMISSION_DENIED;
876        }
877    }
878
879    if (!mModule) {
880        ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
881                callingPid);
882        return -ENODEV;
883    }
884
885    if (getCameraState(cameraId) == nullptr) {
886        ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
887                cameraId.string());
888        return -ENODEV;
889    }
890
891    // Check device policy for this camera
892    char value[PROPERTY_VALUE_MAX];
893    char key[PROPERTY_KEY_MAX];
894    userid_t clientUserId = multiuser_get_user_id(clientUid);
895    snprintf(key, PROPERTY_KEY_MAX, "sys.secpolicy.camera.off_%d", clientUserId);
896    property_get(key, value, "0");
897    if (strcmp(value, "1") == 0) {
898        // Camera is disabled by DevicePolicyManager.
899        ALOGE("CameraService::connect X (PID %d) rejected (camera %s is disabled by device "
900                "policy)", callingPid, cameraId.string());
901        return -EACCES;
902    }
903
904    // Only allow clients who are being used by the current foreground device user, unless calling
905    // from our own process.
906    if (callingPid != getpid() && (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
907        ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
908                "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
909                toString(mAllowedUsers).string());
910        return PERMISSION_DENIED;
911    }
912
913    return checkIfDeviceIsUsable(cameraId);
914}
915
916status_t CameraService::checkIfDeviceIsUsable(const String8& cameraId) const {
917    auto cameraState = getCameraState(cameraId);
918    int callingPid = getCallingPid();
919    if (cameraState == nullptr) {
920        ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
921                cameraId.string());
922        return -ENODEV;
923    }
924
925    ICameraServiceListener::Status currentStatus = cameraState->getStatus();
926    if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
927        ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
928                callingPid, cameraId.string());
929        return -ENODEV;
930    } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
931        ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
932                callingPid, cameraId.string());
933        return -EBUSY;
934    }
935
936    return NO_ERROR;
937}
938
939void CameraService::finishConnectLocked(const sp<BasicClient>& client,
940        const CameraService::DescriptorPtr& desc) {
941
942    // Make a descriptor for the incoming client
943    auto clientDescriptor = CameraService::CameraClientManager::makeClientDescriptor(client, desc);
944    auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
945
946    logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
947            String8(client->getPackageName()));
948
949    if (evicted.size() > 0) {
950        // This should never happen - clients should already have been removed in disconnect
951        for (auto& i : evicted) {
952            ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
953                    __FUNCTION__, i->getKey().string());
954        }
955
956        LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
957                __FUNCTION__);
958    }
959
960    // And register a death notification for the client callback. Do
961    // this last to avoid Binder policy where a nested Binder
962    // transaction might be pre-empted to service the client death
963    // notification if the client process dies before linkToDeath is
964    // invoked.
965    sp<IBinder> remoteCallback = client->getRemote();
966    if (remoteCallback != nullptr) {
967        remoteCallback->linkToDeath(this);
968    }
969}
970
971status_t CameraService::handleEvictionsLocked(const String8& cameraId, int clientPid,
972        apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
973        /*out*/
974        sp<BasicClient>* client,
975        std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial) {
976    ATRACE_CALL();
977    status_t ret = NO_ERROR;
978    std::vector<DescriptorPtr> evictedClients;
979    DescriptorPtr clientDescriptor;
980    {
981        if (effectiveApiLevel == API_1) {
982            // If we are using API1, any existing client for this camera ID with the same remote
983            // should be returned rather than evicted to allow MediaRecorder to work properly.
984
985            auto current = mActiveClientManager.get(cameraId);
986            if (current != nullptr) {
987                auto clientSp = current->getValue();
988                if (clientSp.get() != nullptr) { // should never be needed
989                    if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
990                        ALOGW("CameraService connect called from same client, but with a different"
991                                " API level, evicting prior client...");
992                    } else if (clientSp->getRemote() == remoteCallback) {
993                        ALOGI("CameraService::connect X (PID %d) (second call from same"
994                                " app binder, returning the same client)", clientPid);
995                        *client = clientSp;
996                        return NO_ERROR;
997                    }
998                }
999            }
1000        }
1001
1002        // Return error if the device was unplugged or removed by the HAL for some reason
1003        if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1004            return ret;
1005        }
1006
1007        // Get current active client PIDs
1008        std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1009        ownerPids.push_back(clientPid);
1010
1011        // Use the value +PROCESS_STATE_NONEXISTENT, to avoid taking
1012        // address of PROCESS_STATE_NONEXISTENT as a reference argument
1013        // for the vector constructor. PROCESS_STATE_NONEXISTENT does
1014        // not have an out-of-class definition.
1015        std::vector<int> priorities(ownerPids.size(), +PROCESS_STATE_NONEXISTENT);
1016
1017        // Get priorites of all active PIDs
1018        ProcessInfoService::getProcessStatesFromPids(ownerPids.size(), &ownerPids[0],
1019                /*out*/&priorities[0]);
1020
1021        // Update all active clients' priorities
1022        std::map<int,int> pidToPriorityMap;
1023        for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1024            pidToPriorityMap.emplace(ownerPids[i], getCameraPriorityFromProcState(priorities[i]));
1025        }
1026        mActiveClientManager.updatePriorities(pidToPriorityMap);
1027
1028        // Get state for the given cameraId
1029        auto state = getCameraState(cameraId);
1030        if (state == nullptr) {
1031            ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
1032                clientPid, cameraId.string());
1033            return BAD_VALUE;
1034        }
1035
1036        // Make descriptor for incoming client
1037        clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1038                sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1039                state->getConflicting(),
1040                getCameraPriorityFromProcState(priorities[priorities.size() - 1]), clientPid);
1041
1042        // Find clients that would be evicted
1043        auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1044
1045        // If the incoming client was 'evicted,' higher priority clients have the camera in the
1046        // background, so we cannot do evictions
1047        if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1048            ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1049                    " priority).", clientPid);
1050
1051            sp<BasicClient> clientSp = clientDescriptor->getValue();
1052            String8 curTime = getFormattedCurrentTime();
1053            auto incompatibleClients =
1054                    mActiveClientManager.getIncompatibleClients(clientDescriptor);
1055
1056            String8 msg = String8::format("%s : DENIED connect device %s client for package %s "
1057                    "(PID %d, priority %d) due to eviction policy", curTime.string(),
1058                    cameraId.string(), packageName.string(), clientPid,
1059                    getCameraPriorityFromProcState(priorities[priorities.size() - 1]));
1060
1061            for (auto& i : incompatibleClients) {
1062                msg.appendFormat("\n   - Blocked by existing device %s client for package %s"
1063                        "(PID %" PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1064                        String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1065                        i->getPriority());
1066                ALOGE("   Conflicts with: Device %s, client package %s (PID %"
1067                        PRId32 ", priority %" PRId32 ")", i->getKey().string(),
1068                        String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
1069                        i->getPriority());
1070            }
1071
1072            // Log the client's attempt
1073            Mutex::Autolock l(mLogLock);
1074            mEventLog.add(msg);
1075
1076            return -EBUSY;
1077        }
1078
1079        for (auto& i : evicted) {
1080            sp<BasicClient> clientSp = i->getValue();
1081            if (clientSp.get() == nullptr) {
1082                ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1083
1084                // TODO: Remove this
1085                LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1086                        __FUNCTION__);
1087                mActiveClientManager.remove(i);
1088                continue;
1089            }
1090
1091            ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1092                    i->getKey().string());
1093            evictedClients.push_back(i);
1094
1095            // Log the clients evicted
1096            logEvent(String8::format("EVICT device %s client held by package %s (PID"
1097                    " %" PRId32 ", priority %" PRId32 ")\n   - Evicted by device %s client for"
1098                    " package %s (PID %d, priority %" PRId32 ")",
1099                    i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1100                    i->getOwnerId(), i->getPriority(), cameraId.string(),
1101                    packageName.string(), clientPid,
1102                    getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1103
1104            // Notify the client of disconnection
1105            clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1106                    CaptureResultExtras());
1107        }
1108    }
1109
1110    // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1111    // other clients from connecting in mServiceLockWrapper if held
1112    mServiceLock.unlock();
1113
1114    // Clear caller identity temporarily so client disconnect PID checks work correctly
1115    int64_t token = IPCThreadState::self()->clearCallingIdentity();
1116
1117    // Destroy evicted clients
1118    for (auto& i : evictedClients) {
1119        // Disconnect is blocking, and should only have returned when HAL has cleaned up
1120        i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1121    }
1122
1123    IPCThreadState::self()->restoreCallingIdentity(token);
1124
1125    for (const auto& i : evictedClients) {
1126        ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1127                __FUNCTION__, i->getKey().string(), i->getOwnerId());
1128        ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1129        if (ret == TIMED_OUT) {
1130            ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1131                    "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1132                    mActiveClientManager.toString().string());
1133            return -EBUSY;
1134        }
1135        if (ret != NO_ERROR) {
1136            ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1137                    "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1138                    ret, mActiveClientManager.toString().string());
1139            return ret;
1140        }
1141    }
1142
1143    evictedClients.clear();
1144
1145    // Once clients have been disconnected, relock
1146    mServiceLock.lock();
1147
1148    // Check again if the device was unplugged or something while we weren't holding mServiceLock
1149    if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1150        return ret;
1151    }
1152
1153    *partial = clientDescriptor;
1154    return NO_ERROR;
1155}
1156
1157status_t CameraService::connect(
1158        const sp<ICameraClient>& cameraClient,
1159        int cameraId,
1160        const String16& clientPackageName,
1161        int clientUid,
1162        /*out*/
1163        sp<ICamera>& device) {
1164
1165    ATRACE_CALL();
1166    status_t ret = NO_ERROR;
1167    String8 id = String8::format("%d", cameraId);
1168    sp<Client> client = nullptr;
1169    ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
1170            clientPackageName, clientUid, API_1, false, false, /*out*/client);
1171
1172    if(ret != NO_ERROR) {
1173        logRejected(id, getCallingPid(), String8(clientPackageName),
1174                String8::format("%s (%d)", strerror(-ret), ret));
1175        return ret;
1176    }
1177
1178    device = client;
1179    return NO_ERROR;
1180}
1181
1182status_t CameraService::connectLegacy(
1183        const sp<ICameraClient>& cameraClient,
1184        int cameraId, int halVersion,
1185        const String16& clientPackageName,
1186        int clientUid,
1187        /*out*/
1188        sp<ICamera>& device) {
1189
1190    ATRACE_CALL();
1191    String8 id = String8::format("%d", cameraId);
1192    int apiVersion = mModule->getModuleApiVersion();
1193    if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
1194            apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
1195        /*
1196         * Either the HAL version is unspecified in which case this just creates
1197         * a camera client selected by the latest device version, or
1198         * it's a particular version in which case the HAL must supported
1199         * the open_legacy call
1200         */
1201        ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
1202                __FUNCTION__, apiVersion);
1203        logRejected(id, getCallingPid(), String8(clientPackageName),
1204                String8("HAL module version doesn't support legacy HAL connections"));
1205        return INVALID_OPERATION;
1206    }
1207
1208    status_t ret = NO_ERROR;
1209    sp<Client> client = nullptr;
1210    ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1211            clientUid, API_1, true, false, /*out*/client);
1212
1213    if(ret != NO_ERROR) {
1214        logRejected(id, getCallingPid(), String8(clientPackageName),
1215                String8::format("%s (%d)", strerror(-ret), ret));
1216        return ret;
1217    }
1218
1219    device = client;
1220    return NO_ERROR;
1221}
1222
1223status_t CameraService::connectDevice(
1224        const sp<ICameraDeviceCallbacks>& cameraCb,
1225        int cameraId,
1226        const String16& clientPackageName,
1227        int clientUid,
1228        /*out*/
1229        sp<ICameraDeviceUser>& device) {
1230
1231    ATRACE_CALL();
1232    status_t ret = NO_ERROR;
1233    String8 id = String8::format("%d", cameraId);
1234    sp<CameraDeviceClient> client = nullptr;
1235    ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1236            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
1237            /*out*/client);
1238
1239    if(ret != NO_ERROR) {
1240        logRejected(id, getCallingPid(), String8(clientPackageName),
1241                String8::format("%s (%d)", strerror(-ret), ret));
1242        return ret;
1243    }
1244
1245    device = client;
1246    return NO_ERROR;
1247}
1248
1249status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1250        const sp<IBinder>& clientBinder) {
1251
1252    ATRACE_CALL();
1253    if (enabled && clientBinder == nullptr) {
1254        ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1255        return -EINVAL;
1256    }
1257
1258    String8 id = String8(cameraId.string());
1259    int uid = getCallingUid();
1260
1261    // verify id is valid.
1262    auto state = getCameraState(id);
1263    if (state == nullptr) {
1264        ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1265        return -EINVAL;
1266    }
1267
1268    ICameraServiceListener::Status cameraStatus = state->getStatus();
1269    if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1270            cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1271        ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1272        return -EINVAL;
1273    }
1274
1275    {
1276        Mutex::Autolock al(mTorchStatusMutex);
1277        ICameraServiceListener::TorchStatus status;
1278        status_t res = getTorchStatusLocked(id, &status);
1279        if (res) {
1280            ALOGE("%s: getting current torch status failed for camera %s",
1281                    __FUNCTION__, id.string());
1282            return -EINVAL;
1283        }
1284
1285        if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
1286            if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1287                ALOGE("%s: torch mode of camera %s is not available because "
1288                        "camera is in use", __FUNCTION__, id.string());
1289                return -EBUSY;
1290            } else {
1291                ALOGE("%s: torch mode of camera %s is not available due to "
1292                        "insufficient resources", __FUNCTION__, id.string());
1293                return -EUSERS;
1294            }
1295        }
1296    }
1297
1298    {
1299        // Update UID map - this is used in the torch status changed callbacks, so must be done
1300        // before setTorchMode
1301        Mutex::Autolock al(mTorchUidMapMutex);
1302        if (mTorchUidMap.find(id) == mTorchUidMap.end()) {
1303            mTorchUidMap[id].first = uid;
1304            mTorchUidMap[id].second = uid;
1305        } else {
1306            // Set the pending UID
1307            mTorchUidMap[id].first = uid;
1308        }
1309    }
1310
1311    status_t res = mFlashlight->setTorchMode(id, enabled);
1312
1313    if (res) {
1314        ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1315                __FUNCTION__, id.string(), enabled, strerror(-res), res);
1316        return res;
1317    }
1318
1319    {
1320        // update the link to client's death
1321        Mutex::Autolock al(mTorchClientMapMutex);
1322        ssize_t index = mTorchClientMap.indexOfKey(id);
1323        BatteryNotifier& notifier(BatteryNotifier::getInstance());
1324        if (enabled) {
1325            if (index == NAME_NOT_FOUND) {
1326                mTorchClientMap.add(id, clientBinder);
1327            } else {
1328                mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1329                mTorchClientMap.replaceValueAt(index, clientBinder);
1330            }
1331            clientBinder->linkToDeath(this);
1332        } else if (index != NAME_NOT_FOUND) {
1333            mTorchClientMap.valueAt(index)->unlinkToDeath(this);
1334        }
1335    }
1336
1337    return OK;
1338}
1339
1340void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
1341    ATRACE_CALL();
1342
1343    switch(eventId) {
1344        case ICameraService::USER_SWITCHED: {
1345            doUserSwitch(/*newUserIds*/args, /*length*/length);
1346            break;
1347        }
1348        case ICameraService::NO_EVENT:
1349        default: {
1350            ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1351                    eventId);
1352            break;
1353        }
1354    }
1355}
1356
1357status_t CameraService::addListener(const sp<ICameraServiceListener>& listener) {
1358    ATRACE_CALL();
1359
1360    ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1361
1362    if (listener == nullptr) {
1363        ALOGE("%s: Listener must not be null", __FUNCTION__);
1364        return BAD_VALUE;
1365    }
1366
1367    Mutex::Autolock lock(mServiceLock);
1368
1369    {
1370        Mutex::Autolock lock(mStatusListenerLock);
1371        for (auto& it : mListenerList) {
1372            if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1373                ALOGW("%s: Tried to add listener %p which was already subscribed",
1374                      __FUNCTION__, listener.get());
1375                return ALREADY_EXISTS;
1376            }
1377        }
1378
1379        mListenerList.push_back(listener);
1380    }
1381
1382
1383    /* Immediately signal current status to this listener only */
1384    {
1385        Mutex::Autolock lock(mCameraStatesLock);
1386        for (auto& i : mCameraStates) {
1387            // TODO: Update binder to use String16 for camera IDs and remove;
1388            int id = cameraIdToInt(i.first);
1389            if (id == -1) continue;
1390
1391            listener->onStatusChanged(i.second->getStatus(), id);
1392        }
1393    }
1394
1395    /* Immediately signal current torch status to this listener only */
1396    {
1397        Mutex::Autolock al(mTorchStatusMutex);
1398        for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
1399            String16 id = String16(mTorchStatusMap.keyAt(i).string());
1400            listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
1401        }
1402    }
1403
1404    return OK;
1405}
1406
1407status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1408    ATRACE_CALL();
1409
1410    ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1411
1412    if (listener == 0) {
1413        ALOGE("%s: Listener must not be null", __FUNCTION__);
1414        return BAD_VALUE;
1415    }
1416
1417    Mutex::Autolock lock(mServiceLock);
1418
1419    {
1420        Mutex::Autolock lock(mStatusListenerLock);
1421        for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1422            if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1423                mListenerList.erase(it);
1424                return OK;
1425            }
1426        }
1427    }
1428
1429    ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1430          __FUNCTION__, listener.get());
1431
1432    return BAD_VALUE;
1433}
1434
1435status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1436
1437    ATRACE_CALL();
1438    ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1439
1440    if (parameters == NULL) {
1441        ALOGE("%s: parameters must not be null", __FUNCTION__);
1442        return BAD_VALUE;
1443    }
1444
1445    status_t ret = 0;
1446
1447    CameraParameters shimParams;
1448    if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1449        // Error logged by caller
1450        return ret;
1451    }
1452
1453    String8 shimParamsString8 = shimParams.flatten();
1454    String16 shimParamsString16 = String16(shimParamsString8);
1455
1456    *parameters = shimParamsString16;
1457
1458    return OK;
1459}
1460
1461status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1462    ATRACE_CALL();
1463
1464    ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1465
1466    switch (apiVersion) {
1467        case API_VERSION_1:
1468        case API_VERSION_2:
1469            break;
1470        default:
1471            ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1472            return BAD_VALUE;
1473    }
1474
1475    int facing = -1;
1476    int deviceVersion = getDeviceVersion(cameraId, &facing);
1477
1478    switch(deviceVersion) {
1479      case CAMERA_DEVICE_API_VERSION_1_0:
1480      case CAMERA_DEVICE_API_VERSION_2_0:
1481      case CAMERA_DEVICE_API_VERSION_2_1:
1482      case CAMERA_DEVICE_API_VERSION_3_0:
1483      case CAMERA_DEVICE_API_VERSION_3_1:
1484        if (apiVersion == API_VERSION_2) {
1485            ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1486                    __FUNCTION__, cameraId);
1487            return -EOPNOTSUPP;
1488        } else { // if (apiVersion == API_VERSION_1) {
1489            ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1490                    __FUNCTION__, cameraId);
1491            return OK;
1492        }
1493      case CAMERA_DEVICE_API_VERSION_3_2:
1494      case CAMERA_DEVICE_API_VERSION_3_3:
1495        ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1496                __FUNCTION__, cameraId);
1497        return OK;
1498      case -1:
1499        ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1500        return BAD_VALUE;
1501      default:
1502        ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1503        return INVALID_OPERATION;
1504    }
1505
1506    return OK;
1507}
1508
1509void CameraService::removeByClient(const BasicClient* client) {
1510    Mutex::Autolock lock(mServiceLock);
1511    for (auto& i : mActiveClientManager.getAll()) {
1512        auto clientSp = i->getValue();
1513        if (clientSp.get() == client) {
1514            mActiveClientManager.remove(i);
1515        }
1516    }
1517}
1518
1519bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1520    const int callingPid = getCallingPid();
1521    const int servicePid = getpid();
1522    bool ret = false;
1523    {
1524        // Acquire mServiceLock and prevent other clients from connecting
1525        std::unique_ptr<AutoConditionLock> lock =
1526                AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1527
1528
1529        std::vector<sp<BasicClient>> evicted;
1530        for (auto& i : mActiveClientManager.getAll()) {
1531            auto clientSp = i->getValue();
1532            if (clientSp.get() == nullptr) {
1533                ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1534                mActiveClientManager.remove(i);
1535                continue;
1536            }
1537            if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1538                    callingPid == clientSp->getClientPid())) {
1539                mActiveClientManager.remove(i);
1540                evicted.push_back(clientSp);
1541
1542                // Notify the client of disconnection
1543                clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1544                        CaptureResultExtras());
1545            }
1546        }
1547
1548        // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1549        // other clients from connecting in mServiceLockWrapper if held
1550        mServiceLock.unlock();
1551
1552        // Do not clear caller identity, remote caller should be client proccess
1553
1554        for (auto& i : evicted) {
1555            if (i.get() != nullptr) {
1556                i->disconnect();
1557                ret = true;
1558            }
1559        }
1560
1561        // Reacquire mServiceLock
1562        mServiceLock.lock();
1563
1564    } // lock is destroyed, allow further connect calls
1565
1566    return ret;
1567}
1568
1569
1570/**
1571 * Check camera capabilities, such as support for basic color operation
1572 */
1573int CameraService::checkCameraCapabilities(int id, camera_info info, int *latestStrangeCameraId) {
1574
1575    // Assume all devices pre-v3.3 are backward-compatible
1576    bool isBackwardCompatible = true;
1577    if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_0
1578            && info.device_version >= CAMERA_DEVICE_API_VERSION_3_3) {
1579        isBackwardCompatible = false;
1580        status_t res;
1581        camera_metadata_ro_entry_t caps;
1582        res = find_camera_metadata_ro_entry(
1583            info.static_camera_characteristics,
1584            ANDROID_REQUEST_AVAILABLE_CAPABILITIES,
1585            &caps);
1586        if (res != 0) {
1587            ALOGW("%s: Unable to find camera capabilities for camera device %d",
1588                    __FUNCTION__, id);
1589            caps.count = 0;
1590        }
1591        for (size_t i = 0; i < caps.count; i++) {
1592            if (caps.data.u8[i] ==
1593                    ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
1594                isBackwardCompatible = true;
1595                break;
1596            }
1597        }
1598    }
1599
1600    if (!isBackwardCompatible) {
1601        mNumberOfNormalCameras--;
1602        *latestStrangeCameraId = id;
1603    } else {
1604        if (id > *latestStrangeCameraId) {
1605            ALOGE("%s: Normal camera ID %d higher than strange camera ID %d. "
1606                    "This is not allowed due backward-compatibility requirements",
1607                    __FUNCTION__, id, *latestStrangeCameraId);
1608            logServiceError("Invalid order of camera devices", ENODEV);
1609            mNumberOfCameras = 0;
1610            mNumberOfNormalCameras = 0;
1611            return INVALID_OPERATION;
1612        }
1613    }
1614    return OK;
1615}
1616
1617std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1618        const String8& cameraId) const {
1619    std::shared_ptr<CameraState> state;
1620    {
1621        Mutex::Autolock lock(mCameraStatesLock);
1622        auto iter = mCameraStates.find(cameraId);
1623        if (iter != mCameraStates.end()) {
1624            state = iter->second;
1625        }
1626    }
1627    return state;
1628}
1629
1630sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1631    // Remove from active clients list
1632    auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1633    if (clientDescriptorPtr == nullptr) {
1634        ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1635                cameraId.string());
1636        return sp<BasicClient>{nullptr};
1637    }
1638
1639    return clientDescriptorPtr->getValue();
1640}
1641
1642void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
1643    // Acquire mServiceLock and prevent other clients from connecting
1644    std::unique_ptr<AutoConditionLock> lock =
1645            AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1646
1647    std::set<userid_t> newAllowedUsers;
1648    for (size_t i = 0; i < length; i++) {
1649        if (newUserId[i] < 0) {
1650            ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1651                    __FUNCTION__, newUserId[i]);
1652            return;
1653        }
1654        newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
1655    }
1656
1657
1658    if (newAllowedUsers == mAllowedUsers) {
1659        ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1660        return;
1661    }
1662
1663    logUserSwitch(mAllowedUsers, newAllowedUsers);
1664
1665    mAllowedUsers = std::move(newAllowedUsers);
1666
1667    // Current user has switched, evict all current clients.
1668    std::vector<sp<BasicClient>> evicted;
1669    for (auto& i : mActiveClientManager.getAll()) {
1670        auto clientSp = i->getValue();
1671
1672        if (clientSp.get() == nullptr) {
1673            ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1674            continue;
1675        }
1676
1677        // Don't evict clients that are still allowed.
1678        uid_t clientUid = clientSp->getClientUid();
1679        userid_t clientUserId = multiuser_get_user_id(clientUid);
1680        if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1681            continue;
1682        }
1683
1684        evicted.push_back(clientSp);
1685
1686        String8 curTime = getFormattedCurrentTime();
1687
1688        ALOGE("Evicting conflicting client for camera ID %s due to user change",
1689                i->getKey().string());
1690
1691        // Log the clients evicted
1692        logEvent(String8::format("EVICT device %s client held by package %s (PID %"
1693                PRId32 ", priority %" PRId32 ")\n   - Evicted due to user switch.",
1694                i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1695                i->getOwnerId(), i->getPriority()));
1696
1697    }
1698
1699    // Do not hold mServiceLock while disconnecting clients, but retain the condition
1700    // blocking other clients from connecting in mServiceLockWrapper if held.
1701    mServiceLock.unlock();
1702
1703    // Clear caller identity temporarily so client disconnect PID checks work correctly
1704    int64_t token = IPCThreadState::self()->clearCallingIdentity();
1705
1706    for (auto& i : evicted) {
1707        i->disconnect();
1708    }
1709
1710    IPCThreadState::self()->restoreCallingIdentity(token);
1711
1712    // Reacquire mServiceLock
1713    mServiceLock.lock();
1714}
1715
1716void CameraService::logEvent(const char* event) {
1717    String8 curTime = getFormattedCurrentTime();
1718    Mutex::Autolock l(mLogLock);
1719    mEventLog.add(String8::format("%s : %s", curTime.string(), event));
1720}
1721
1722void CameraService::logDisconnected(const char* cameraId, int clientPid,
1723        const char* clientPackage) {
1724    // Log the clients evicted
1725    logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1726            clientPackage, clientPid));
1727}
1728
1729void CameraService::logConnected(const char* cameraId, int clientPid,
1730        const char* clientPackage) {
1731    // Log the clients evicted
1732    logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1733            clientPackage, clientPid));
1734}
1735
1736void CameraService::logRejected(const char* cameraId, int clientPid,
1737        const char* clientPackage, const char* reason) {
1738    // Log the client rejected
1739    logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1740            cameraId, clientPackage, clientPid, reason));
1741}
1742
1743void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1744        const std::set<userid_t>& newUserIds) {
1745    String8 newUsers = toString(newUserIds);
1746    String8 oldUsers = toString(oldUserIds);
1747    // Log the new and old users
1748    logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1749            oldUsers.string(), newUsers.string()));
1750}
1751
1752void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1753    // Log the device removal
1754    logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1755}
1756
1757void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1758    // Log the device removal
1759    logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1760}
1761
1762void CameraService::logClientDied(int clientPid, const char* reason) {
1763    // Log the device removal
1764    logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
1765}
1766
1767void CameraService::logServiceError(const char* msg, int errorCode) {
1768    String8 curTime = getFormattedCurrentTime();
1769    logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1770}
1771
1772status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1773        uint32_t flags) {
1774
1775    const int pid = getCallingPid();
1776    const int selfPid = getpid();
1777
1778    // Permission checks
1779    switch (code) {
1780        case BnCameraService::CONNECT:
1781        case BnCameraService::CONNECT_DEVICE:
1782        case BnCameraService::CONNECT_LEGACY: {
1783            if (pid != selfPid) {
1784                // we're called from a different process, do the real check
1785                if (!checkCallingPermission(
1786                        String16("android.permission.CAMERA"))) {
1787                    const int uid = getCallingUid();
1788                    ALOGE("Permission Denial: "
1789                         "can't use the camera pid=%d, uid=%d", pid, uid);
1790                    return PERMISSION_DENIED;
1791                }
1792            }
1793            break;
1794        }
1795        case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1796            if (pid != selfPid) {
1797                // Ensure we're being called by system_server, or similar process with
1798                // permissions to notify the camera service about system events
1799                if (!checkCallingPermission(
1800                        String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1801                    const int uid = getCallingUid();
1802                    ALOGE("Permission Denial: cannot send updates to camera service about system"
1803                            " events from pid=%d, uid=%d", pid, uid);
1804                    return PERMISSION_DENIED;
1805                }
1806            }
1807            break;
1808        }
1809    }
1810
1811    return BnCameraService::onTransact(code, data, reply, flags);
1812}
1813
1814// We share the media players for shutter and recording sound for all clients.
1815// A reference count is kept to determine when we will actually release the
1816// media players.
1817
1818MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1819    MediaPlayer* mp = new MediaPlayer();
1820    if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1821        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1822        mp->prepare();
1823    } else {
1824        ALOGE("Failed to load CameraService sounds: %s", file);
1825        return NULL;
1826    }
1827    return mp;
1828}
1829
1830void CameraService::loadSound() {
1831    ATRACE_CALL();
1832
1833    Mutex::Autolock lock(mSoundLock);
1834    LOG1("CameraService::loadSound ref=%d", mSoundRef);
1835    if (mSoundRef++) return;
1836
1837    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1838    mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1839    mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
1840}
1841
1842void CameraService::releaseSound() {
1843    Mutex::Autolock lock(mSoundLock);
1844    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1845    if (--mSoundRef) return;
1846
1847    for (int i = 0; i < NUM_SOUNDS; i++) {
1848        if (mSoundPlayer[i] != 0) {
1849            mSoundPlayer[i]->disconnect();
1850            mSoundPlayer[i].clear();
1851        }
1852    }
1853}
1854
1855void CameraService::playSound(sound_kind kind) {
1856    ATRACE_CALL();
1857
1858    LOG1("playSound(%d)", kind);
1859    Mutex::Autolock lock(mSoundLock);
1860    sp<MediaPlayer> player = mSoundPlayer[kind];
1861    if (player != 0) {
1862        player->seekTo(0);
1863        player->start();
1864    }
1865}
1866
1867// ----------------------------------------------------------------------------
1868
1869CameraService::Client::Client(const sp<CameraService>& cameraService,
1870        const sp<ICameraClient>& cameraClient,
1871        const String16& clientPackageName,
1872        int cameraId, int cameraFacing,
1873        int clientPid, uid_t clientUid,
1874        int servicePid) :
1875        CameraService::BasicClient(cameraService,
1876                IInterface::asBinder(cameraClient),
1877                clientPackageName,
1878                cameraId, cameraFacing,
1879                clientPid, clientUid,
1880                servicePid)
1881{
1882    int callingPid = getCallingPid();
1883    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1884
1885    mRemoteCallback = cameraClient;
1886
1887    cameraService->loadSound();
1888
1889    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1890}
1891
1892// tear down the client
1893CameraService::Client::~Client() {
1894    ALOGV("~Client");
1895    mDestructionStarted = true;
1896
1897    mCameraService->releaseSound();
1898    // unconditionally disconnect. function is idempotent
1899    Client::disconnect();
1900}
1901
1902CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1903        const sp<IBinder>& remoteCallback,
1904        const String16& clientPackageName,
1905        int cameraId, int cameraFacing,
1906        int clientPid, uid_t clientUid,
1907        int servicePid):
1908        mClientPackageName(clientPackageName), mDisconnected(false)
1909{
1910    mCameraService = cameraService;
1911    mRemoteBinder = remoteCallback;
1912    mCameraId = cameraId;
1913    mCameraFacing = cameraFacing;
1914    mClientPid = clientPid;
1915    mClientUid = clientUid;
1916    mServicePid = servicePid;
1917    mOpsActive = false;
1918    mDestructionStarted = false;
1919}
1920
1921CameraService::BasicClient::~BasicClient() {
1922    ALOGV("~BasicClient");
1923    mDestructionStarted = true;
1924}
1925
1926void CameraService::BasicClient::disconnect() {
1927    if (mDisconnected) {
1928        return;
1929    }
1930    mDisconnected = true;
1931
1932    mCameraService->removeByClient(this);
1933    mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1934            String8(mClientPackageName));
1935
1936    sp<IBinder> remote = getRemote();
1937    if (remote != nullptr) {
1938        remote->unlinkToDeath(mCameraService);
1939    }
1940
1941    finishCameraOps();
1942    ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1943
1944    // client shouldn't be able to call into us anymore
1945    mClientPid = 0;
1946}
1947
1948String16 CameraService::BasicClient::getPackageName() const {
1949    return mClientPackageName;
1950}
1951
1952
1953int CameraService::BasicClient::getClientPid() const {
1954    return mClientPid;
1955}
1956
1957uid_t CameraService::BasicClient::getClientUid() const {
1958    return mClientUid;
1959}
1960
1961bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1962    // Defaults to API2.
1963    return level == API_2;
1964}
1965
1966status_t CameraService::BasicClient::startCameraOps() {
1967    ATRACE_CALL();
1968
1969    int32_t res;
1970    // Notify app ops that the camera is not available
1971    mOpsCallback = new OpsCallback(this);
1972
1973    {
1974        ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1975              __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1976    }
1977
1978    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1979            mClientPackageName, mOpsCallback);
1980    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1981            mClientUid, mClientPackageName);
1982
1983    if (res == AppOpsManager::MODE_ERRORED) {
1984        ALOGI("Camera %d: Access for \"%s\" has been revoked",
1985                mCameraId, String8(mClientPackageName).string());
1986        return PERMISSION_DENIED;
1987    }
1988
1989    if (res == AppOpsManager::MODE_IGNORED) {
1990        ALOGI("Camera %d: Access for \"%s\" has been restricted",
1991                mCameraId, String8(mClientPackageName).string());
1992        // Return the same error as for device policy manager rejection
1993        return -EACCES;
1994    }
1995
1996    mOpsActive = true;
1997
1998    // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1999    mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
2000            String8::format("%d", mCameraId));
2001
2002    // Transition device state to OPEN
2003    mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_OPEN,
2004            String8::format("%d", mCameraId));
2005
2006    return OK;
2007}
2008
2009status_t CameraService::BasicClient::finishCameraOps() {
2010    ATRACE_CALL();
2011
2012    // Check if startCameraOps succeeded, and if so, finish the camera op
2013    if (mOpsActive) {
2014        // Notify app ops that the camera is available again
2015        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
2016                mClientPackageName);
2017        mOpsActive = false;
2018
2019        auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
2020                ICameraServiceListener::STATUS_ENUMERATING};
2021
2022        // Transition to PRESENT if the camera is not in either of the rejected states
2023        mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
2024                String8::format("%d", mCameraId), rejected);
2025
2026        // Transition device state to CLOSED
2027        mCameraService->updateProxyDeviceState(ICameraServiceProxy::CAMERA_STATE_CLOSED,
2028                String8::format("%d", mCameraId));
2029
2030        // Notify flashlight that a camera device is closed.
2031        mCameraService->mFlashlight->deviceClosed(
2032                String8::format("%d", mCameraId));
2033    }
2034    // Always stop watching, even if no camera op is active
2035    if (mOpsCallback != NULL) {
2036        mAppOpsManager.stopWatchingMode(mOpsCallback);
2037    }
2038    mOpsCallback.clear();
2039
2040    return OK;
2041}
2042
2043void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
2044    ATRACE_CALL();
2045
2046    String8 name(packageName);
2047    String8 myName(mClientPackageName);
2048
2049    if (op != AppOpsManager::OP_CAMERA) {
2050        ALOGW("Unexpected app ops notification received: %d", op);
2051        return;
2052    }
2053
2054    int32_t res;
2055    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
2056            mClientUid, mClientPackageName);
2057    ALOGV("checkOp returns: %d, %s ", res,
2058            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
2059            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
2060            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
2061            "UNKNOWN");
2062
2063    if (res != AppOpsManager::MODE_ALLOWED) {
2064        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
2065                myName.string());
2066        // Reset the client PID to allow server-initiated disconnect,
2067        // and to prevent further calls by client.
2068        mClientPid = getCallingPid();
2069        CaptureResultExtras resultExtras; // a dummy result (invalid)
2070        notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
2071        disconnect();
2072    }
2073}
2074
2075// ----------------------------------------------------------------------------
2076
2077// Provide client strong pointer for callbacks.
2078sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
2079    String8 cameraId = String8::format("%d", (int)(intptr_t) user);
2080    auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
2081    if (clientDescriptor != nullptr) {
2082        return sp<Client>{
2083                static_cast<Client*>(clientDescriptor->getValue().get())};
2084    }
2085    return sp<Client>{nullptr};
2086}
2087
2088void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
2089        const CaptureResultExtras& resultExtras) {
2090    if (mRemoteCallback != NULL) {
2091        mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
2092    } else {
2093        ALOGE("mRemoteCallback is NULL!!");
2094    }
2095}
2096
2097// NOTE: function is idempotent
2098void CameraService::Client::disconnect() {
2099    ALOGV("Client::disconnect");
2100    BasicClient::disconnect();
2101}
2102
2103bool CameraService::Client::canCastToApiClient(apiLevel level) const {
2104    return level == API_1;
2105}
2106
2107CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
2108        mClient(client) {
2109}
2110
2111void CameraService::Client::OpsCallback::opChanged(int32_t op,
2112        const String16& packageName) {
2113    sp<BasicClient> client = mClient.promote();
2114    if (client != NULL) {
2115        client->opChanged(op, packageName);
2116    }
2117}
2118
2119// ----------------------------------------------------------------------------
2120//                  CameraState
2121// ----------------------------------------------------------------------------
2122
2123CameraService::CameraState::CameraState(const String8& id, int cost,
2124        const std::set<String8>& conflicting) : mId(id),
2125        mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
2126
2127CameraService::CameraState::~CameraState() {}
2128
2129ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
2130    Mutex::Autolock lock(mStatusLock);
2131    return mStatus;
2132}
2133
2134CameraParameters CameraService::CameraState::getShimParams() const {
2135    return mShimParams;
2136}
2137
2138void CameraService::CameraState::setShimParams(const CameraParameters& params) {
2139    mShimParams = params;
2140}
2141
2142int CameraService::CameraState::getCost() const {
2143    return mCost;
2144}
2145
2146std::set<String8> CameraService::CameraState::getConflicting() const {
2147    return mConflicting;
2148}
2149
2150String8 CameraService::CameraState::getId() const {
2151    return mId;
2152}
2153
2154// ----------------------------------------------------------------------------
2155//                  ClientEventListener
2156// ----------------------------------------------------------------------------
2157
2158void CameraService::ClientEventListener::onClientAdded(
2159        const resource_policy::ClientDescriptor<String8,
2160        sp<CameraService::BasicClient>>& descriptor) {
2161    auto basicClient = descriptor.getValue();
2162    if (basicClient.get() != nullptr) {
2163        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2164        notifier.noteStartCamera(descriptor.getKey(),
2165                static_cast<int>(basicClient->getClientUid()));
2166    }
2167}
2168
2169void CameraService::ClientEventListener::onClientRemoved(
2170        const resource_policy::ClientDescriptor<String8,
2171        sp<CameraService::BasicClient>>& descriptor) {
2172    auto basicClient = descriptor.getValue();
2173    if (basicClient.get() != nullptr) {
2174        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2175        notifier.noteStopCamera(descriptor.getKey(),
2176                static_cast<int>(basicClient->getClientUid()));
2177    }
2178}
2179
2180
2181// ----------------------------------------------------------------------------
2182//                  CameraClientManager
2183// ----------------------------------------------------------------------------
2184
2185CameraService::CameraClientManager::CameraClientManager() {
2186    setListener(std::make_shared<ClientEventListener>());
2187}
2188
2189CameraService::CameraClientManager::~CameraClientManager() {}
2190
2191sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
2192        const String8& id) const {
2193    auto descriptor = get(id);
2194    if (descriptor == nullptr) {
2195        return sp<BasicClient>{nullptr};
2196    }
2197    return descriptor->getValue();
2198}
2199
2200String8 CameraService::CameraClientManager::toString() const {
2201    auto all = getAll();
2202    String8 ret("[");
2203    bool hasAny = false;
2204    for (auto& i : all) {
2205        hasAny = true;
2206        String8 key = i->getKey();
2207        int32_t cost = i->getCost();
2208        int32_t pid = i->getOwnerId();
2209        int32_t priority = i->getPriority();
2210        auto conflicting = i->getConflicting();
2211        auto clientSp = i->getValue();
2212        String8 packageName;
2213        userid_t clientUserId = 0;
2214        if (clientSp.get() != nullptr) {
2215            packageName = String8{clientSp->getPackageName()};
2216            uid_t clientUid = clientSp->getClientUid();
2217            clientUserId = multiuser_get_user_id(clientUid);
2218        }
2219        ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2220                PRId32 ", ", key.string(), cost, pid, priority);
2221
2222        if (clientSp.get() != nullptr) {
2223            ret.appendFormat("User Id: %d, ", clientUserId);
2224        }
2225        if (packageName.size() != 0) {
2226            ret.appendFormat("Client Package Name: %s", packageName.string());
2227        }
2228
2229        ret.append(", Conflicting Client Devices: {");
2230        for (auto& j : conflicting) {
2231            ret.appendFormat("%s, ", j.string());
2232        }
2233        ret.append("})");
2234    }
2235    if (hasAny) ret.append("\n");
2236    ret.append("]\n");
2237    return ret;
2238}
2239
2240CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2241        const String8& key, const sp<BasicClient>& value, int32_t cost,
2242        const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2243
2244    return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2245            key, value, cost, conflictingKeys, priority, ownerId);
2246}
2247
2248CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2249        const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2250    return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2251            partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2252}
2253
2254// ----------------------------------------------------------------------------
2255
2256static const int kDumpLockRetries = 50;
2257static const int kDumpLockSleep = 60000;
2258
2259static bool tryLock(Mutex& mutex)
2260{
2261    bool locked = false;
2262    for (int i = 0; i < kDumpLockRetries; ++i) {
2263        if (mutex.tryLock() == NO_ERROR) {
2264            locked = true;
2265            break;
2266        }
2267        usleep(kDumpLockSleep);
2268    }
2269    return locked;
2270}
2271
2272status_t CameraService::dump(int fd, const Vector<String16>& args) {
2273    ATRACE_CALL();
2274
2275    String8 result("Dump of the Camera Service:\n");
2276    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
2277        result = result.format("Permission Denial: "
2278                "can't dump CameraService from pid=%d, uid=%d\n",
2279                getCallingPid(),
2280                getCallingUid());
2281        write(fd, result.string(), result.size());
2282    } else {
2283        bool locked = tryLock(mServiceLock);
2284        // failed to lock - CameraService is probably deadlocked
2285        if (!locked) {
2286            result.append("CameraService may be deadlocked\n");
2287            write(fd, result.string(), result.size());
2288        }
2289
2290        bool hasClient = false;
2291        if (!mModule) {
2292            result = String8::format("No camera module available!\n");
2293            write(fd, result.string(), result.size());
2294
2295            // Dump event log for error information
2296            dumpEventLog(fd);
2297
2298            if (locked) mServiceLock.unlock();
2299            return NO_ERROR;
2300        }
2301
2302        result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2303        result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2304        result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2305        result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
2306        result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2307        String8 activeClientString = mActiveClientManager.toString();
2308        result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2309        result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
2310
2311        sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2312        if (desc == NULL) {
2313            result.appendFormat("Vendor tags left unimplemented.\n");
2314        } else {
2315            result.appendFormat("Vendor tag definitions:\n");
2316        }
2317
2318        write(fd, result.string(), result.size());
2319
2320        if (desc != NULL) {
2321            desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2322        }
2323
2324        dumpEventLog(fd);
2325
2326        bool stateLocked = tryLock(mCameraStatesLock);
2327        if (!stateLocked) {
2328            result = String8::format("CameraStates in use, may be deadlocked\n");
2329            write(fd, result.string(), result.size());
2330        }
2331
2332        for (auto& state : mCameraStates) {
2333            String8 cameraId = state.first;
2334            result = String8::format("Camera %s information:\n", cameraId.string());
2335            camera_info info;
2336
2337            // TODO: Change getCameraInfo + HAL to use String cameraIds
2338            status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
2339            if (rc != OK) {
2340                result.appendFormat("  Error reading static information!\n");
2341                write(fd, result.string(), result.size());
2342            } else {
2343                result.appendFormat("  Facing: %s\n",
2344                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2345                result.appendFormat("  Orientation: %d\n", info.orientation);
2346                int deviceVersion;
2347                if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
2348                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2349                } else {
2350                    deviceVersion = info.device_version;
2351                }
2352
2353                auto conflicting = state.second->getConflicting();
2354                result.appendFormat("  Resource Cost: %d\n", state.second->getCost());
2355                result.appendFormat("  Conflicting Devices:");
2356                for (auto& id : conflicting) {
2357                    result.appendFormat(" %s", cameraId.string());
2358                }
2359                if (conflicting.size() == 0) {
2360                    result.appendFormat(" NONE");
2361                }
2362                result.appendFormat("\n");
2363
2364                result.appendFormat("  Device version: %#x\n", deviceVersion);
2365                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2366                    result.appendFormat("  Device static metadata:\n");
2367                    write(fd, result.string(), result.size());
2368                    dump_indented_camera_metadata(info.static_camera_characteristics,
2369                            fd, /*verbosity*/2, /*indentation*/4);
2370                } else {
2371                    write(fd, result.string(), result.size());
2372                }
2373
2374                CameraParameters p = state.second->getShimParams();
2375                if (!p.isEmpty()) {
2376                    result = String8::format("  Camera1 API shim is using parameters:\n        ");
2377                    write(fd, result.string(), result.size());
2378                    p.dump(fd, args);
2379                }
2380            }
2381
2382            auto clientDescriptor = mActiveClientManager.get(cameraId);
2383            if (clientDescriptor == nullptr) {
2384                result = String8::format("  Device %s is closed, no client instance\n",
2385                        cameraId.string());
2386                write(fd, result.string(), result.size());
2387                continue;
2388            }
2389            hasClient = true;
2390            result = String8::format("  Device %s is open. Client instance dump:\n\n",
2391                    cameraId.string());
2392            result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2393            result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2394
2395            auto client = clientDescriptor->getValue();
2396            result.appendFormat("Client package: %s\n",
2397                    String8(client->getPackageName()).string());
2398            write(fd, result.string(), result.size());
2399
2400            client->dump(fd, args);
2401        }
2402
2403        if (stateLocked) mCameraStatesLock.unlock();
2404
2405        if (!hasClient) {
2406            result = String8::format("\nNo active camera clients yet.\n");
2407            write(fd, result.string(), result.size());
2408        }
2409
2410        if (locked) mServiceLock.unlock();
2411
2412        // Dump camera traces if there were any
2413        write(fd, "\n", 1);
2414        camera3::CameraTraces::dump(fd, args);
2415
2416        // change logging level
2417        int n = args.size();
2418        for (int i = 0; i + 1 < n; i++) {
2419            String16 verboseOption("-v");
2420            if (args[i] == verboseOption) {
2421                String8 levelStr(args[i+1]);
2422                int level = atoi(levelStr.string());
2423                result = String8::format("\nSetting log level to %d.\n", level);
2424                setLogLevel(level);
2425                write(fd, result.string(), result.size());
2426            }
2427        }
2428    }
2429    return NO_ERROR;
2430}
2431
2432void CameraService::dumpEventLog(int fd) {
2433    String8 result = String8("\nPrior client events (most recent at top):\n");
2434
2435    Mutex::Autolock l(mLogLock);
2436    for (const auto& msg : mEventLog) {
2437        result.appendFormat("  %s\n", msg.string());
2438    }
2439
2440    if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2441        result.append("  ...\n");
2442    } else if (mEventLog.size() == 0) {
2443        result.append("  [no events yet]\n");
2444    }
2445    result.append("\n");
2446
2447    write(fd, result.string(), result.size());
2448}
2449
2450void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
2451    Mutex::Autolock al(mTorchClientMapMutex);
2452    for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2453        if (mTorchClientMap[i] == who) {
2454            // turn off the torch mode that was turned on by dead client
2455            String8 cameraId = mTorchClientMap.keyAt(i);
2456            status_t res = mFlashlight->setTorchMode(cameraId, false);
2457            if (res) {
2458                ALOGE("%s: torch client died but couldn't turn off torch: "
2459                    "%s (%d)", __FUNCTION__, strerror(-res), res);
2460                return;
2461            }
2462            mTorchClientMap.removeItemsAt(i);
2463            break;
2464        }
2465    }
2466}
2467
2468/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
2469
2470    /**
2471      * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2472      * binder driver
2473      */
2474
2475    logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2476
2477    // check torch client
2478    handleTorchClientBinderDied(who);
2479
2480    // check camera device client
2481    if(!evictClientIdByRemote(who)) {
2482        ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
2483        return;
2484    }
2485
2486    ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2487            __FUNCTION__);
2488}
2489
2490void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2491    updateStatus(status, cameraId, {});
2492}
2493
2494void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2495        std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2496    // Do not lock mServiceLock here or can get into a deadlock from
2497    // connect() -> disconnect -> updateStatus
2498
2499    auto state = getCameraState(cameraId);
2500
2501    if (state == nullptr) {
2502        ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2503                cameraId.string());
2504        return;
2505    }
2506
2507    // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2508    // of the listeners with both the mStatusStatus and mStatusListenerLock held
2509    state->updateStatus(status, cameraId, rejectSourceStates, [this]
2510            (const String8& cameraId, ICameraServiceListener::Status status) {
2511
2512            if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2513                // Update torch status if it has a flash unit.
2514                Mutex::Autolock al(mTorchStatusMutex);
2515                ICameraServiceListener::TorchStatus torchStatus;
2516                if (getTorchStatusLocked(cameraId, &torchStatus) !=
2517                        NAME_NOT_FOUND) {
2518                    ICameraServiceListener::TorchStatus newTorchStatus =
2519                            status == ICameraServiceListener::STATUS_PRESENT ?
2520                            ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2521                            ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2522                    if (torchStatus != newTorchStatus) {
2523                        onTorchStatusChangedLocked(cameraId, newTorchStatus);
2524                    }
2525                }
2526            }
2527
2528            Mutex::Autolock lock(mStatusListenerLock);
2529
2530            for (auto& listener : mListenerList) {
2531                // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2532                int id = cameraIdToInt(cameraId);
2533                if (id != -1) listener->onStatusChanged(status, id);
2534            }
2535        });
2536}
2537
2538void CameraService::updateProxyDeviceState(ICameraServiceProxy::CameraState newState,
2539        const String8& cameraId) {
2540    sp<ICameraServiceProxy> proxyBinder = getCameraServiceProxy();
2541    if (proxyBinder == nullptr) return;
2542    String16 id(cameraId);
2543    proxyBinder->notifyCameraState(id, newState);
2544}
2545
2546status_t CameraService::getTorchStatusLocked(
2547        const String8& cameraId,
2548        ICameraServiceListener::TorchStatus *status) const {
2549    if (!status) {
2550        return BAD_VALUE;
2551    }
2552    ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2553    if (index == NAME_NOT_FOUND) {
2554        // invalid camera ID or the camera doesn't have a flash unit
2555        return NAME_NOT_FOUND;
2556    }
2557
2558    *status = mTorchStatusMap.valueAt(index);
2559    return OK;
2560}
2561
2562status_t CameraService::setTorchStatusLocked(const String8& cameraId,
2563        ICameraServiceListener::TorchStatus status) {
2564    ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2565    if (index == NAME_NOT_FOUND) {
2566        return BAD_VALUE;
2567    }
2568    ICameraServiceListener::TorchStatus& item =
2569            mTorchStatusMap.editValueAt(index);
2570    item = status;
2571
2572    return OK;
2573}
2574
2575}; // namespace android
2576