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