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