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