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