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