CameraService.cpp revision 2232aee25e4df7d04446912e8ad9e9dc44d8ec16
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                ALOGE("   Conflicts with: Device %s, client package %s (PID %"
976                        PRId32 ", priority %" PRId32 ")", i->getKey().string(),
977                        String8{i->getValue()->getPackageName()}.string(), i->getOwnerId(),
978                        i->getPriority());
979            }
980
981            // Log the client's attempt
982            Mutex::Autolock l(mLogLock);
983            mEventLog.add(msg);
984
985            return -EBUSY;
986        }
987
988        for (auto& i : evicted) {
989            sp<BasicClient> clientSp = i->getValue();
990            if (clientSp.get() == nullptr) {
991                ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
992
993                // TODO: Remove this
994                LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
995                        __FUNCTION__);
996                mActiveClientManager.remove(i);
997                continue;
998            }
999
1000            ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
1001                    i->getKey().string());
1002            evictedClients.push_back(i);
1003
1004            // Log the clients evicted
1005            logEvent(String8::format("EVICT device %s client held by package %s (PID"
1006                    " %" PRId32 ", priority %" PRId32 ")\n   - Evicted by device %s client for"
1007                    " package %s (PID %d, priority %" PRId32 ")",
1008                    i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1009                    i->getOwnerId(), i->getPriority(), cameraId.string(),
1010                    packageName.string(), clientPid,
1011                    getCameraPriorityFromProcState(priorities[priorities.size() - 1])));
1012
1013            // Notify the client of disconnection
1014            clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1015                    CaptureResultExtras());
1016        }
1017    }
1018
1019    // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1020    // other clients from connecting in mServiceLockWrapper if held
1021    mServiceLock.unlock();
1022
1023    // Clear caller identity temporarily so client disconnect PID checks work correctly
1024    int64_t token = IPCThreadState::self()->clearCallingIdentity();
1025
1026    // Destroy evicted clients
1027    for (auto& i : evictedClients) {
1028        // Disconnect is blocking, and should only have returned when HAL has cleaned up
1029        i->getValue()->disconnect(); // Clients will remove themselves from the active client list
1030    }
1031
1032    IPCThreadState::self()->restoreCallingIdentity(token);
1033
1034    for (const auto& i : evictedClients) {
1035        ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
1036                __FUNCTION__, i->getKey().string(), i->getOwnerId());
1037        ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1038        if (ret == TIMED_OUT) {
1039            ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
1040                    "current clients:\n%s", __FUNCTION__, i->getKey().string(),
1041                    mActiveClientManager.toString().string());
1042            return -EBUSY;
1043        }
1044        if (ret != NO_ERROR) {
1045            ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
1046                    "current clients:\n%s", __FUNCTION__, i->getKey().string(), strerror(-ret),
1047                    ret, mActiveClientManager.toString().string());
1048            return ret;
1049        }
1050    }
1051
1052    evictedClients.clear();
1053
1054    // Once clients have been disconnected, relock
1055    mServiceLock.lock();
1056
1057    // Check again if the device was unplugged or something while we weren't holding mServiceLock
1058    if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1059        return ret;
1060    }
1061
1062    *partial = clientDescriptor;
1063    return NO_ERROR;
1064}
1065
1066status_t CameraService::connect(
1067        const sp<ICameraClient>& cameraClient,
1068        int cameraId,
1069        const String16& clientPackageName,
1070        int clientUid,
1071        /*out*/
1072        sp<ICamera>& device) {
1073
1074    status_t ret = NO_ERROR;
1075    String8 id = String8::format("%d", cameraId);
1076    sp<Client> client = nullptr;
1077    ret = connectHelper<ICameraClient,Client>(cameraClient, id, CAMERA_HAL_API_VERSION_UNSPECIFIED,
1078            clientPackageName, clientUid, API_1, false, false, /*out*/client);
1079
1080    if(ret != NO_ERROR) {
1081        logRejected(id, getCallingPid(), String8(clientPackageName),
1082                String8::format("%s (%d)", strerror(-ret), ret));
1083        return ret;
1084    }
1085
1086    device = client;
1087    return NO_ERROR;
1088}
1089
1090status_t CameraService::connectLegacy(
1091        const sp<ICameraClient>& cameraClient,
1092        int cameraId, int halVersion,
1093        const String16& clientPackageName,
1094        int clientUid,
1095        /*out*/
1096        sp<ICamera>& device) {
1097
1098    String8 id = String8::format("%d", cameraId);
1099    int apiVersion = mModule->getModuleApiVersion();
1100    if (halVersion != CAMERA_HAL_API_VERSION_UNSPECIFIED &&
1101            apiVersion < CAMERA_MODULE_API_VERSION_2_3) {
1102        /*
1103         * Either the HAL version is unspecified in which case this just creates
1104         * a camera client selected by the latest device version, or
1105         * it's a particular version in which case the HAL must supported
1106         * the open_legacy call
1107         */
1108        ALOGE("%s: camera HAL module version %x doesn't support connecting to legacy HAL devices!",
1109                __FUNCTION__, apiVersion);
1110        logRejected(id, getCallingPid(), String8(clientPackageName),
1111                String8("HAL module version doesn't support legacy HAL connections"));
1112        return INVALID_OPERATION;
1113    }
1114
1115    status_t ret = NO_ERROR;
1116    sp<Client> client = nullptr;
1117    ret = connectHelper<ICameraClient,Client>(cameraClient, id, halVersion, clientPackageName,
1118            clientUid, API_1, true, false, /*out*/client);
1119
1120    if(ret != NO_ERROR) {
1121        logRejected(id, getCallingPid(), String8(clientPackageName),
1122                String8::format("%s (%d)", strerror(-ret), ret));
1123        return ret;
1124    }
1125
1126    device = client;
1127    return NO_ERROR;
1128}
1129
1130status_t CameraService::connectDevice(
1131        const sp<ICameraDeviceCallbacks>& cameraCb,
1132        int cameraId,
1133        const String16& clientPackageName,
1134        int clientUid,
1135        /*out*/
1136        sp<ICameraDeviceUser>& device) {
1137
1138    status_t ret = NO_ERROR;
1139    String8 id = String8::format("%d", cameraId);
1140    sp<CameraDeviceClient> client = nullptr;
1141    ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
1142            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
1143            /*out*/client);
1144
1145    if(ret != NO_ERROR) {
1146        logRejected(id, getCallingPid(), String8(clientPackageName),
1147                String8::format("%s (%d)", strerror(-ret), ret));
1148        return ret;
1149    }
1150
1151    device = client;
1152    return NO_ERROR;
1153}
1154
1155status_t CameraService::setTorchMode(const String16& cameraId, bool enabled,
1156        const sp<IBinder>& clientBinder) {
1157    if (enabled && clientBinder == NULL) {
1158        ALOGE("%s: torch client binder is NULL", __FUNCTION__);
1159        return -EINVAL;
1160    }
1161
1162    String8 id = String8(cameraId.string());
1163
1164    // verify id is valid.
1165    auto state = getCameraState(id);
1166    if (state == nullptr) {
1167        ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1168        return -EINVAL;
1169    }
1170
1171    ICameraServiceListener::Status cameraStatus = state->getStatus();
1172    if (cameraStatus != ICameraServiceListener::STATUS_PRESENT &&
1173            cameraStatus != ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1174        ALOGE("%s: camera id is invalid %s", __FUNCTION__, id.string());
1175        return -EINVAL;
1176    }
1177
1178    {
1179        Mutex::Autolock al(mTorchStatusMutex);
1180        ICameraServiceListener::TorchStatus status;
1181        status_t res = getTorchStatusLocked(id, &status);
1182        if (res) {
1183            ALOGE("%s: getting current torch status failed for camera %s",
1184                    __FUNCTION__, id.string());
1185            return -EINVAL;
1186        }
1187
1188        if (status == ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE) {
1189            if (cameraStatus == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1190                ALOGE("%s: torch mode of camera %s is not available because "
1191                        "camera is in use", __FUNCTION__, id.string());
1192                return -EBUSY;
1193            } else {
1194                ALOGE("%s: torch mode of camera %s is not available due to "
1195                        "insufficient resources", __FUNCTION__, id.string());
1196                return -EUSERS;
1197            }
1198        }
1199    }
1200
1201    status_t res = mFlashlight->setTorchMode(id, enabled);
1202    if (res) {
1203        ALOGE("%s: setting torch mode of camera %s to %d failed. %s (%d)",
1204                __FUNCTION__, id.string(), enabled, strerror(-res), res);
1205        return res;
1206    }
1207
1208    {
1209        // update the link to client's death
1210        Mutex::Autolock al(mTorchClientMapMutex);
1211        ssize_t index = mTorchClientMap.indexOfKey(id);
1212        if (enabled) {
1213            if (index == NAME_NOT_FOUND) {
1214                mTorchClientMap.add(id, clientBinder);
1215            } else {
1216                const sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
1217                oldBinder->unlinkToDeath(this);
1218
1219                mTorchClientMap.replaceValueAt(index, clientBinder);
1220            }
1221            clientBinder->linkToDeath(this);
1222        } else if (index != NAME_NOT_FOUND) {
1223            sp<IBinder> oldBinder = mTorchClientMap.valueAt(index);
1224            oldBinder->unlinkToDeath(this);
1225        }
1226    }
1227
1228    return OK;
1229}
1230
1231void CameraService::notifySystemEvent(int32_t eventId, const int32_t* args, size_t length) {
1232    switch(eventId) {
1233        case ICameraService::USER_SWITCHED: {
1234            doUserSwitch(/*newUserIds*/args, /*length*/length);
1235            break;
1236        }
1237        case ICameraService::NO_EVENT:
1238        default: {
1239            ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
1240                    eventId);
1241            break;
1242        }
1243    }
1244}
1245
1246status_t CameraService::addListener(
1247                                const sp<ICameraServiceListener>& listener) {
1248    ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
1249
1250    if (listener == 0) {
1251        ALOGE("%s: Listener must not be null", __FUNCTION__);
1252        return BAD_VALUE;
1253    }
1254
1255    Mutex::Autolock lock(mServiceLock);
1256
1257    {
1258        Mutex::Autolock lock(mStatusListenerLock);
1259        for (auto& it : mListenerList) {
1260            if (IInterface::asBinder(it) == IInterface::asBinder(listener)) {
1261                ALOGW("%s: Tried to add listener %p which was already subscribed",
1262                      __FUNCTION__, listener.get());
1263                return ALREADY_EXISTS;
1264            }
1265        }
1266
1267        mListenerList.push_back(listener);
1268    }
1269
1270
1271    /* Immediately signal current status to this listener only */
1272    {
1273        Mutex::Autolock lock(mCameraStatesLock);
1274        for (auto& i : mCameraStates) {
1275            // TODO: Update binder to use String16 for camera IDs and remove;
1276            int id = cameraIdToInt(i.first);
1277            if (id == -1) continue;
1278
1279            listener->onStatusChanged(i.second->getStatus(), id);
1280        }
1281    }
1282
1283    /* Immediately signal current torch status to this listener only */
1284    {
1285        Mutex::Autolock al(mTorchStatusMutex);
1286        for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
1287            String16 id = String16(mTorchStatusMap.keyAt(i).string());
1288            listener->onTorchStatusChanged(mTorchStatusMap.valueAt(i), id);
1289        }
1290    }
1291
1292    return OK;
1293}
1294
1295status_t CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
1296    ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
1297
1298    if (listener == 0) {
1299        ALOGE("%s: Listener must not be null", __FUNCTION__);
1300        return BAD_VALUE;
1301    }
1302
1303    Mutex::Autolock lock(mServiceLock);
1304
1305    {
1306        Mutex::Autolock lock(mStatusListenerLock);
1307        for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
1308            if (IInterface::asBinder(*it) == IInterface::asBinder(listener)) {
1309                mListenerList.erase(it);
1310                return OK;
1311            }
1312        }
1313    }
1314
1315    ALOGW("%s: Tried to remove a listener %p which was not subscribed",
1316          __FUNCTION__, listener.get());
1317
1318    return BAD_VALUE;
1319}
1320
1321status_t CameraService::getLegacyParameters(int cameraId, /*out*/String16* parameters) {
1322    ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1323
1324    if (parameters == NULL) {
1325        ALOGE("%s: parameters must not be null", __FUNCTION__);
1326        return BAD_VALUE;
1327    }
1328
1329    status_t ret = 0;
1330
1331    CameraParameters shimParams;
1332    if ((ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)) != OK) {
1333        // Error logged by caller
1334        return ret;
1335    }
1336
1337    String8 shimParamsString8 = shimParams.flatten();
1338    String16 shimParamsString16 = String16(shimParamsString8);
1339
1340    *parameters = shimParamsString16;
1341
1342    return OK;
1343}
1344
1345status_t CameraService::supportsCameraApi(int cameraId, int apiVersion) {
1346    ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
1347
1348    switch (apiVersion) {
1349        case API_VERSION_1:
1350        case API_VERSION_2:
1351            break;
1352        default:
1353            ALOGE("%s: Bad API version %d", __FUNCTION__, apiVersion);
1354            return BAD_VALUE;
1355    }
1356
1357    int facing = -1;
1358    int deviceVersion = getDeviceVersion(cameraId, &facing);
1359
1360    switch(deviceVersion) {
1361      case CAMERA_DEVICE_API_VERSION_1_0:
1362      case CAMERA_DEVICE_API_VERSION_2_0:
1363      case CAMERA_DEVICE_API_VERSION_2_1:
1364      case CAMERA_DEVICE_API_VERSION_3_0:
1365      case CAMERA_DEVICE_API_VERSION_3_1:
1366        if (apiVersion == API_VERSION_2) {
1367            ALOGV("%s: Camera id %d uses HAL prior to HAL3.2, doesn't support api2 without shim",
1368                    __FUNCTION__, cameraId);
1369            return -EOPNOTSUPP;
1370        } else { // if (apiVersion == API_VERSION_1) {
1371            ALOGV("%s: Camera id %d uses older HAL before 3.2, but api1 is always supported",
1372                    __FUNCTION__, cameraId);
1373            return OK;
1374        }
1375      case CAMERA_DEVICE_API_VERSION_3_2:
1376      case CAMERA_DEVICE_API_VERSION_3_3:
1377        ALOGV("%s: Camera id %d uses HAL3.2 or newer, supports api1/api2 directly",
1378                __FUNCTION__, cameraId);
1379        return OK;
1380      case -1:
1381        ALOGE("%s: Invalid camera id %d", __FUNCTION__, cameraId);
1382        return BAD_VALUE;
1383      default:
1384        ALOGE("%s: Unknown camera device HAL version: %d", __FUNCTION__, deviceVersion);
1385        return INVALID_OPERATION;
1386    }
1387
1388    return OK;
1389}
1390
1391void CameraService::removeByClient(const BasicClient* client) {
1392    Mutex::Autolock lock(mServiceLock);
1393    for (auto& i : mActiveClientManager.getAll()) {
1394        auto clientSp = i->getValue();
1395        if (clientSp.get() == client) {
1396            mActiveClientManager.remove(i);
1397        }
1398    }
1399}
1400
1401bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
1402    const int callingPid = getCallingPid();
1403    const int servicePid = getpid();
1404    bool ret = false;
1405    {
1406        // Acquire mServiceLock and prevent other clients from connecting
1407        std::unique_ptr<AutoConditionLock> lock =
1408                AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1409
1410
1411        std::vector<sp<BasicClient>> evicted;
1412        for (auto& i : mActiveClientManager.getAll()) {
1413            auto clientSp = i->getValue();
1414            if (clientSp.get() == nullptr) {
1415                ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1416                mActiveClientManager.remove(i);
1417                continue;
1418            }
1419            if (remote == clientSp->getRemote() && (callingPid == servicePid ||
1420                    callingPid == clientSp->getClientPid())) {
1421                mActiveClientManager.remove(i);
1422                evicted.push_back(clientSp);
1423
1424                // Notify the client of disconnection
1425                clientSp->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
1426                        CaptureResultExtras());
1427            }
1428        }
1429
1430        // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1431        // other clients from connecting in mServiceLockWrapper if held
1432        mServiceLock.unlock();
1433
1434        // Do not clear caller identity, remote caller should be client proccess
1435
1436        for (auto& i : evicted) {
1437            if (i.get() != nullptr) {
1438                i->disconnect();
1439                ret = true;
1440            }
1441        }
1442
1443        // Reacquire mServiceLock
1444        mServiceLock.lock();
1445
1446    } // lock is destroyed, allow further connect calls
1447
1448    return ret;
1449}
1450
1451
1452std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
1453        const String8& cameraId) const {
1454    std::shared_ptr<CameraState> state;
1455    {
1456        Mutex::Autolock lock(mCameraStatesLock);
1457        auto iter = mCameraStates.find(cameraId);
1458        if (iter != mCameraStates.end()) {
1459            state = iter->second;
1460        }
1461    }
1462    return state;
1463}
1464
1465sp<CameraService::BasicClient> CameraService::removeClientLocked(const String8& cameraId) {
1466    // Remove from active clients list
1467    auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
1468    if (clientDescriptorPtr == nullptr) {
1469        ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
1470                cameraId.string());
1471        return sp<BasicClient>{nullptr};
1472    }
1473
1474    return clientDescriptorPtr->getValue();
1475}
1476
1477void CameraService::doUserSwitch(const int32_t* newUserId, size_t length) {
1478    // Acquire mServiceLock and prevent other clients from connecting
1479    std::unique_ptr<AutoConditionLock> lock =
1480            AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1481
1482    std::set<userid_t> newAllowedUsers;
1483    for (size_t i = 0; i < length; i++) {
1484        if (newUserId[i] < 0) {
1485            ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
1486                    __FUNCTION__, newUserId[i]);
1487            return;
1488        }
1489        newAllowedUsers.insert(static_cast<userid_t>(newUserId[i]));
1490    }
1491
1492
1493    if (newAllowedUsers == mAllowedUsers) {
1494        ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
1495        return;
1496    }
1497
1498    logUserSwitch(mAllowedUsers, newAllowedUsers);
1499
1500    mAllowedUsers = std::move(newAllowedUsers);
1501
1502    // Current user has switched, evict all current clients.
1503    std::vector<sp<BasicClient>> evicted;
1504    for (auto& i : mActiveClientManager.getAll()) {
1505        auto clientSp = i->getValue();
1506
1507        if (clientSp.get() == nullptr) {
1508            ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
1509            continue;
1510        }
1511
1512        // Don't evict clients that are still allowed.
1513        uid_t clientUid = clientSp->getClientUid();
1514        userid_t clientUserId = multiuser_get_user_id(clientUid);
1515        if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
1516            continue;
1517        }
1518
1519        evicted.push_back(clientSp);
1520
1521        String8 curTime = getFormattedCurrentTime();
1522
1523        ALOGE("Evicting conflicting client for camera ID %s due to user change",
1524                i->getKey().string());
1525
1526        // Log the clients evicted
1527        logEvent(String8::format("EVICT device %s client held by package %s (PID %"
1528                PRId32 ", priority %" PRId32 ")\n   - Evicted due to user switch.",
1529                i->getKey().string(), String8{clientSp->getPackageName()}.string(),
1530                i->getOwnerId(), i->getPriority()));
1531
1532    }
1533
1534    // Do not hold mServiceLock while disconnecting clients, but retain the condition
1535    // blocking other clients from connecting in mServiceLockWrapper if held.
1536    mServiceLock.unlock();
1537
1538    // Clear caller identity temporarily so client disconnect PID checks work correctly
1539    int64_t token = IPCThreadState::self()->clearCallingIdentity();
1540
1541    for (auto& i : evicted) {
1542        i->disconnect();
1543    }
1544
1545    IPCThreadState::self()->restoreCallingIdentity(token);
1546
1547    // Reacquire mServiceLock
1548    mServiceLock.lock();
1549}
1550
1551void CameraService::logEvent(const char* event) {
1552    String8 curTime = getFormattedCurrentTime();
1553    Mutex::Autolock l(mLogLock);
1554    mEventLog.add(String8::format("%s : %s", curTime.string(), event));
1555}
1556
1557void CameraService::logDisconnected(const char* cameraId, int clientPid,
1558        const char* clientPackage) {
1559    // Log the clients evicted
1560    logEvent(String8::format("DISCONNECT device %s client for package %s (PID %d)", cameraId,
1561            clientPackage, clientPid));
1562}
1563
1564void CameraService::logConnected(const char* cameraId, int clientPid,
1565        const char* clientPackage) {
1566    // Log the clients evicted
1567    logEvent(String8::format("CONNECT device %s client for package %s (PID %d)", cameraId,
1568            clientPackage, clientPid));
1569}
1570
1571void CameraService::logRejected(const char* cameraId, int clientPid,
1572        const char* clientPackage, const char* reason) {
1573    // Log the client rejected
1574    logEvent(String8::format("REJECT device %s client for package %s (PID %d), reason: (%s)",
1575            cameraId, clientPackage, clientPid, reason));
1576}
1577
1578void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
1579        const std::set<userid_t>& newUserIds) {
1580    String8 newUsers = toString(newUserIds);
1581    String8 oldUsers = toString(oldUserIds);
1582    // Log the new and old users
1583    logEvent(String8::format("USER_SWITCH previous allowed users: %s , current allowed users: %s",
1584            oldUsers.string(), newUsers.string()));
1585}
1586
1587void CameraService::logDeviceRemoved(const char* cameraId, const char* reason) {
1588    // Log the device removal
1589    logEvent(String8::format("REMOVE device %s, reason: (%s)", cameraId, reason));
1590}
1591
1592void CameraService::logDeviceAdded(const char* cameraId, const char* reason) {
1593    // Log the device removal
1594    logEvent(String8::format("ADD device %s, reason: (%s)", cameraId, reason));
1595}
1596
1597void CameraService::logClientDied(int clientPid, const char* reason) {
1598    // Log the device removal
1599    logEvent(String8::format("DIED client(s) with PID %d, reason: (%s)", clientPid, reason));
1600}
1601
1602void CameraService::logServiceError(const char* msg, int errorCode) {
1603    String8 curTime = getFormattedCurrentTime();
1604    logEvent(String8::format("SERVICE ERROR: %s : %d (%s)", msg, errorCode, strerror(errorCode)));
1605}
1606
1607status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
1608        uint32_t flags) {
1609
1610    const int pid = getCallingPid();
1611    const int selfPid = getpid();
1612
1613    // Permission checks
1614    switch (code) {
1615        case BnCameraService::CONNECT:
1616        case BnCameraService::CONNECT_DEVICE:
1617        case BnCameraService::CONNECT_LEGACY: {
1618            if (pid != selfPid) {
1619                // we're called from a different process, do the real check
1620                if (!checkCallingPermission(
1621                        String16("android.permission.CAMERA"))) {
1622                    const int uid = getCallingUid();
1623                    ALOGE("Permission Denial: "
1624                         "can't use the camera pid=%d, uid=%d", pid, uid);
1625                    return PERMISSION_DENIED;
1626                }
1627            }
1628            break;
1629        }
1630        case BnCameraService::NOTIFY_SYSTEM_EVENT: {
1631            if (pid != selfPid) {
1632                // Ensure we're being called by system_server, or similar process with
1633                // permissions to notify the camera service about system events
1634                if (!checkCallingPermission(
1635                        String16("android.permission.CAMERA_SEND_SYSTEM_EVENTS"))) {
1636                    const int uid = getCallingUid();
1637                    ALOGE("Permission Denial: cannot send updates to camera service about system"
1638                            " events from pid=%d, uid=%d", pid, uid);
1639                    return PERMISSION_DENIED;
1640                }
1641            }
1642            break;
1643        }
1644    }
1645
1646    return BnCameraService::onTransact(code, data, reply, flags);
1647}
1648
1649// We share the media players for shutter and recording sound for all clients.
1650// A reference count is kept to determine when we will actually release the
1651// media players.
1652
1653MediaPlayer* CameraService::newMediaPlayer(const char *file) {
1654    MediaPlayer* mp = new MediaPlayer();
1655    if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
1656        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
1657        mp->prepare();
1658    } else {
1659        ALOGE("Failed to load CameraService sounds: %s", file);
1660        return NULL;
1661    }
1662    return mp;
1663}
1664
1665void CameraService::loadSound() {
1666    Mutex::Autolock lock(mSoundLock);
1667    LOG1("CameraService::loadSound ref=%d", mSoundRef);
1668    if (mSoundRef++) return;
1669
1670    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
1671    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
1672}
1673
1674void CameraService::releaseSound() {
1675    Mutex::Autolock lock(mSoundLock);
1676    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
1677    if (--mSoundRef) return;
1678
1679    for (int i = 0; i < NUM_SOUNDS; i++) {
1680        if (mSoundPlayer[i] != 0) {
1681            mSoundPlayer[i]->disconnect();
1682            mSoundPlayer[i].clear();
1683        }
1684    }
1685}
1686
1687void CameraService::playSound(sound_kind kind) {
1688    LOG1("playSound(%d)", kind);
1689    Mutex::Autolock lock(mSoundLock);
1690    sp<MediaPlayer> player = mSoundPlayer[kind];
1691    if (player != 0) {
1692        player->seekTo(0);
1693        player->start();
1694    }
1695}
1696
1697// ----------------------------------------------------------------------------
1698
1699CameraService::Client::Client(const sp<CameraService>& cameraService,
1700        const sp<ICameraClient>& cameraClient,
1701        const String16& clientPackageName,
1702        int cameraId, int cameraFacing,
1703        int clientPid, uid_t clientUid,
1704        int servicePid) :
1705        CameraService::BasicClient(cameraService,
1706                IInterface::asBinder(cameraClient),
1707                clientPackageName,
1708                cameraId, cameraFacing,
1709                clientPid, clientUid,
1710                servicePid)
1711{
1712    int callingPid = getCallingPid();
1713    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1714
1715    mRemoteCallback = cameraClient;
1716
1717    cameraService->loadSound();
1718
1719    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1720}
1721
1722// tear down the client
1723CameraService::Client::~Client() {
1724    ALOGV("~Client");
1725    mDestructionStarted = true;
1726
1727    mCameraService->releaseSound();
1728    // unconditionally disconnect. function is idempotent
1729    Client::disconnect();
1730}
1731
1732CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1733        const sp<IBinder>& remoteCallback,
1734        const String16& clientPackageName,
1735        int cameraId, int cameraFacing,
1736        int clientPid, uid_t clientUid,
1737        int servicePid):
1738        mClientPackageName(clientPackageName), mDisconnected(false)
1739{
1740    mCameraService = cameraService;
1741    mRemoteBinder = remoteCallback;
1742    mCameraId = cameraId;
1743    mCameraFacing = cameraFacing;
1744    mClientPid = clientPid;
1745    mClientUid = clientUid;
1746    mServicePid = servicePid;
1747    mOpsActive = false;
1748    mDestructionStarted = false;
1749}
1750
1751CameraService::BasicClient::~BasicClient() {
1752    ALOGV("~BasicClient");
1753    mDestructionStarted = true;
1754}
1755
1756void CameraService::BasicClient::disconnect() {
1757    if (mDisconnected) {
1758        ALOGE("%s: Disconnect called on already disconnected client for device %d", __FUNCTION__,
1759                mCameraId);
1760        return;
1761    }
1762    mDisconnected = true;;
1763
1764    mCameraService->removeByClient(this);
1765    mCameraService->logDisconnected(String8::format("%d", mCameraId), mClientPid,
1766            String8(mClientPackageName));
1767
1768    sp<IBinder> remote = getRemote();
1769    if (remote != nullptr) {
1770        remote->unlinkToDeath(mCameraService);
1771    }
1772
1773    finishCameraOps();
1774    ALOGI("%s: Disconnected client for camera %d for PID %d", __FUNCTION__, mCameraId, mClientPid);
1775
1776    // client shouldn't be able to call into us anymore
1777    mClientPid = 0;
1778}
1779
1780String16 CameraService::BasicClient::getPackageName() const {
1781    return mClientPackageName;
1782}
1783
1784
1785int CameraService::BasicClient::getClientPid() const {
1786    return mClientPid;
1787}
1788
1789uid_t CameraService::BasicClient::getClientUid() const {
1790    return mClientUid;
1791}
1792
1793bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
1794    // Defaults to API2.
1795    return level == API_2;
1796}
1797
1798status_t CameraService::BasicClient::startCameraOps() {
1799    int32_t res;
1800    // Notify app ops that the camera is not available
1801    mOpsCallback = new OpsCallback(this);
1802
1803    {
1804        ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1805              __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1806    }
1807
1808    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1809            mClientPackageName, mOpsCallback);
1810    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1811            mClientUid, mClientPackageName);
1812
1813    if (res == AppOpsManager::MODE_ERRORED) {
1814        ALOGI("Camera %d: Access for \"%s\" has been revoked",
1815                mCameraId, String8(mClientPackageName).string());
1816        return PERMISSION_DENIED;
1817    }
1818
1819    if (res == AppOpsManager::MODE_IGNORED) {
1820        ALOGI("Camera %d: Access for \"%s\" has been restricted",
1821                mCameraId, String8(mClientPackageName).string());
1822        return INVALID_OPERATION;
1823    }
1824
1825    mOpsActive = true;
1826
1827    // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
1828    mCameraService->updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
1829            String8::format("%d", mCameraId));
1830
1831    return OK;
1832}
1833
1834status_t CameraService::BasicClient::finishCameraOps() {
1835    // Check if startCameraOps succeeded, and if so, finish the camera op
1836    if (mOpsActive) {
1837        // Notify app ops that the camera is available again
1838        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1839                mClientPackageName);
1840        mOpsActive = false;
1841
1842        auto rejected = {ICameraServiceListener::STATUS_NOT_PRESENT,
1843                ICameraServiceListener::STATUS_ENUMERATING};
1844
1845        // Transition to PRESENT if the camera is not in either of the rejected states
1846        mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
1847                String8::format("%d", mCameraId), rejected);
1848
1849        // Notify flashlight that a camera device is closed.
1850        mCameraService->mFlashlight->deviceClosed(
1851                String8::format("%d", mCameraId));
1852    }
1853    // Always stop watching, even if no camera op is active
1854    if (mOpsCallback != NULL) {
1855        mAppOpsManager.stopWatchingMode(mOpsCallback);
1856    }
1857    mOpsCallback.clear();
1858
1859    return OK;
1860}
1861
1862void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1863    String8 name(packageName);
1864    String8 myName(mClientPackageName);
1865
1866    if (op != AppOpsManager::OP_CAMERA) {
1867        ALOGW("Unexpected app ops notification received: %d", op);
1868        return;
1869    }
1870
1871    int32_t res;
1872    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1873            mClientUid, mClientPackageName);
1874    ALOGV("checkOp returns: %d, %s ", res,
1875            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1876            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1877            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1878            "UNKNOWN");
1879
1880    if (res != AppOpsManager::MODE_ALLOWED) {
1881        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1882                myName.string());
1883        // Reset the client PID to allow server-initiated disconnect,
1884        // and to prevent further calls by client.
1885        mClientPid = getCallingPid();
1886        CaptureResultExtras resultExtras; // a dummy result (invalid)
1887        notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
1888        disconnect();
1889    }
1890}
1891
1892// ----------------------------------------------------------------------------
1893
1894// Provide client strong pointer for callbacks.
1895sp<CameraService::Client> CameraService::Client::getClientFromCookie(void* user) {
1896    String8 cameraId = String8::format("%d", (int)(intptr_t) user);
1897    auto clientDescriptor = gCameraService->mActiveClientManager.get(cameraId);
1898    if (clientDescriptor != nullptr) {
1899        return sp<Client>{
1900                static_cast<Client*>(clientDescriptor->getValue().get())};
1901    }
1902    return sp<Client>{nullptr};
1903}
1904
1905void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1906        const CaptureResultExtras& resultExtras) {
1907    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1908}
1909
1910// NOTE: function is idempotent
1911void CameraService::Client::disconnect() {
1912    ALOGV("Client::disconnect");
1913    BasicClient::disconnect();
1914}
1915
1916bool CameraService::Client::canCastToApiClient(apiLevel level) const {
1917    return level == API_1;
1918}
1919
1920CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1921        mClient(client) {
1922}
1923
1924void CameraService::Client::OpsCallback::opChanged(int32_t op,
1925        const String16& packageName) {
1926    sp<BasicClient> client = mClient.promote();
1927    if (client != NULL) {
1928        client->opChanged(op, packageName);
1929    }
1930}
1931
1932// ----------------------------------------------------------------------------
1933//                  CameraState
1934// ----------------------------------------------------------------------------
1935
1936CameraService::CameraState::CameraState(const String8& id, int cost,
1937        const std::set<String8>& conflicting) : mId(id),
1938        mStatus(ICameraServiceListener::STATUS_PRESENT), mCost(cost), mConflicting(conflicting) {}
1939
1940CameraService::CameraState::~CameraState() {}
1941
1942ICameraServiceListener::Status CameraService::CameraState::getStatus() const {
1943    Mutex::Autolock lock(mStatusLock);
1944    return mStatus;
1945}
1946
1947CameraParameters CameraService::CameraState::getShimParams() const {
1948    return mShimParams;
1949}
1950
1951void CameraService::CameraState::setShimParams(const CameraParameters& params) {
1952    mShimParams = params;
1953}
1954
1955int CameraService::CameraState::getCost() const {
1956    return mCost;
1957}
1958
1959std::set<String8> CameraService::CameraState::getConflicting() const {
1960    return mConflicting;
1961}
1962
1963String8 CameraService::CameraState::getId() const {
1964    return mId;
1965}
1966
1967// ----------------------------------------------------------------------------
1968//                  CameraClientManager
1969// ----------------------------------------------------------------------------
1970
1971CameraService::CameraClientManager::~CameraClientManager() {}
1972
1973sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
1974        const String8& id) const {
1975    auto descriptor = get(id);
1976    if (descriptor == nullptr) {
1977        return sp<BasicClient>{nullptr};
1978    }
1979    return descriptor->getValue();
1980}
1981
1982String8 CameraService::CameraClientManager::toString() const {
1983    auto all = getAll();
1984    String8 ret("[");
1985    bool hasAny = false;
1986    for (auto& i : all) {
1987        hasAny = true;
1988        String8 key = i->getKey();
1989        int32_t cost = i->getCost();
1990        int32_t pid = i->getOwnerId();
1991        int32_t priority = i->getPriority();
1992        auto conflicting = i->getConflicting();
1993        auto clientSp = i->getValue();
1994        String8 packageName;
1995        userid_t clientUserId = 0;
1996        if (clientSp.get() != nullptr) {
1997            packageName = String8{clientSp->getPackageName()};
1998            uid_t clientUid = clientSp->getClientUid();
1999            clientUserId = multiuser_get_user_id(clientUid);
2000        }
2001        ret.appendFormat("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Priority: %"
2002                PRId32 ", ", key.string(), cost, pid, priority);
2003
2004        if (clientSp.get() != nullptr) {
2005            ret.appendFormat("User Id: %d, ", clientUserId);
2006        }
2007        if (packageName.size() != 0) {
2008            ret.appendFormat("Client Package Name: %s", packageName.string());
2009        }
2010
2011        ret.append(", Conflicting Client Devices: {");
2012        for (auto& j : conflicting) {
2013            ret.appendFormat("%s, ", j.string());
2014        }
2015        ret.append("})");
2016    }
2017    if (hasAny) ret.append("\n");
2018    ret.append("]\n");
2019    return ret;
2020}
2021
2022CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2023        const String8& key, const sp<BasicClient>& value, int32_t cost,
2024        const std::set<String8>& conflictingKeys, int32_t priority, int32_t ownerId) {
2025
2026    return std::make_shared<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>(
2027            key, value, cost, conflictingKeys, priority, ownerId);
2028}
2029
2030CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
2031        const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial) {
2032    return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
2033            partial->getConflicting(), partial->getPriority(), partial->getOwnerId());
2034}
2035
2036// ----------------------------------------------------------------------------
2037
2038static const int kDumpLockRetries = 50;
2039static const int kDumpLockSleep = 60000;
2040
2041static bool tryLock(Mutex& mutex)
2042{
2043    bool locked = false;
2044    for (int i = 0; i < kDumpLockRetries; ++i) {
2045        if (mutex.tryLock() == NO_ERROR) {
2046            locked = true;
2047            break;
2048        }
2049        usleep(kDumpLockSleep);
2050    }
2051    return locked;
2052}
2053
2054status_t CameraService::dump(int fd, const Vector<String16>& args) {
2055    String8 result("Dump of the Camera Service:\n");
2056    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
2057        result.appendFormat("Permission Denial: "
2058                "can't dump CameraService from pid=%d, uid=%d\n",
2059                getCallingPid(),
2060                getCallingUid());
2061        write(fd, result.string(), result.size());
2062    } else {
2063        bool locked = tryLock(mServiceLock);
2064        // failed to lock - CameraService is probably deadlocked
2065        if (!locked) {
2066            result.append("CameraService may be deadlocked\n");
2067            write(fd, result.string(), result.size());
2068        }
2069
2070        bool hasClient = false;
2071        if (!mModule) {
2072            result = String8::format("No camera module available!\n");
2073            write(fd, result.string(), result.size());
2074
2075            // Dump event log for error information
2076            dumpEventLog(fd);
2077
2078            if (locked) mServiceLock.unlock();
2079            return NO_ERROR;
2080        }
2081
2082        result = String8::format("Camera module HAL API version: 0x%x\n", mModule->getHalApiVersion());
2083        result.appendFormat("Camera module API version: 0x%x\n", mModule->getModuleApiVersion());
2084        result.appendFormat("Camera module name: %s\n", mModule->getModuleName());
2085        result.appendFormat("Camera module author: %s\n", mModule->getModuleAuthor());
2086        result.appendFormat("Number of camera devices: %d\n", mNumberOfCameras);
2087        String8 activeClientString = mActiveClientManager.toString();
2088        result.appendFormat("Active Camera Clients:\n%s", activeClientString.string());
2089        result.appendFormat("Allowed users:\n%s\n", toString(mAllowedUsers).string());
2090
2091        sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2092        if (desc == NULL) {
2093            result.appendFormat("Vendor tags left unimplemented.\n");
2094        } else {
2095            result.appendFormat("Vendor tag definitions:\n");
2096        }
2097
2098        write(fd, result.string(), result.size());
2099
2100        if (desc != NULL) {
2101            desc->dump(fd, /*verbosity*/2, /*indentation*/4);
2102        }
2103
2104        dumpEventLog(fd);
2105
2106        bool stateLocked = tryLock(mCameraStatesLock);
2107        if (!stateLocked) {
2108            result = String8::format("CameraStates in use, may be deadlocked\n");
2109            write(fd, result.string(), result.size());
2110        }
2111
2112        for (auto& state : mCameraStates) {
2113            String8 cameraId = state.first;
2114            result = String8::format("Camera %s information:\n", cameraId.string());
2115            camera_info info;
2116
2117            // TODO: Change getCameraInfo + HAL to use String cameraIds
2118            status_t rc = mModule->getCameraInfo(cameraIdToInt(cameraId), &info);
2119            if (rc != OK) {
2120                result.appendFormat("  Error reading static information!\n");
2121                write(fd, result.string(), result.size());
2122            } else {
2123                result.appendFormat("  Facing: %s\n",
2124                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
2125                result.appendFormat("  Orientation: %d\n", info.orientation);
2126                int deviceVersion;
2127                if (mModule->getModuleApiVersion() < CAMERA_MODULE_API_VERSION_2_0) {
2128                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
2129                } else {
2130                    deviceVersion = info.device_version;
2131                }
2132
2133                auto conflicting = state.second->getConflicting();
2134                result.appendFormat("  Resource Cost: %d\n", state.second->getCost());
2135                result.appendFormat("  Conflicting Devices:");
2136                for (auto& id : conflicting) {
2137                    result.appendFormat(" %s", cameraId.string());
2138                }
2139                if (conflicting.size() == 0) {
2140                    result.appendFormat(" NONE");
2141                }
2142                result.appendFormat("\n");
2143
2144                result.appendFormat("  Device version: %#x\n", deviceVersion);
2145                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
2146                    result.appendFormat("  Device static metadata:\n");
2147                    write(fd, result.string(), result.size());
2148                    dump_indented_camera_metadata(info.static_camera_characteristics,
2149                            fd, /*verbosity*/2, /*indentation*/4);
2150                } else {
2151                    write(fd, result.string(), result.size());
2152                }
2153
2154                CameraParameters p = state.second->getShimParams();
2155                if (!p.isEmpty()) {
2156                    result = String8::format("  Camera1 API shim is using parameters:\n        ");
2157                    write(fd, result.string(), result.size());
2158                    p.dump(fd, args);
2159                }
2160            }
2161
2162            auto clientDescriptor = mActiveClientManager.get(cameraId);
2163            if (clientDescriptor == nullptr) {
2164                result = String8::format("  Device %s is closed, no client instance\n",
2165                        cameraId.string());
2166                write(fd, result.string(), result.size());
2167                continue;
2168            }
2169            hasClient = true;
2170            result = String8::format("  Device %s is open. Client instance dump:\n\n",
2171                    cameraId.string());
2172            result.appendFormat("Client priority level: %d\n", clientDescriptor->getPriority());
2173            result.appendFormat("Client PID: %d\n", clientDescriptor->getOwnerId());
2174
2175            auto client = clientDescriptor->getValue();
2176            result.appendFormat("Client package: %s\n",
2177                    String8(client->getPackageName()).string());
2178            write(fd, result.string(), result.size());
2179
2180            client->dump(fd, args);
2181        }
2182
2183        if (stateLocked) mCameraStatesLock.unlock();
2184
2185        if (!hasClient) {
2186            result = String8::format("\nNo active camera clients yet.\n");
2187            write(fd, result.string(), result.size());
2188        }
2189
2190        if (locked) mServiceLock.unlock();
2191
2192        // Dump camera traces if there were any
2193        write(fd, "\n", 1);
2194        camera3::CameraTraces::dump(fd, args);
2195
2196        // change logging level
2197        int n = args.size();
2198        for (int i = 0; i + 1 < n; i++) {
2199            String16 verboseOption("-v");
2200            if (args[i] == verboseOption) {
2201                String8 levelStr(args[i+1]);
2202                int level = atoi(levelStr.string());
2203                result = String8::format("\nSetting log level to %d.\n", level);
2204                setLogLevel(level);
2205                write(fd, result.string(), result.size());
2206            }
2207        }
2208    }
2209    return NO_ERROR;
2210}
2211
2212void CameraService::dumpEventLog(int fd) {
2213    String8 result = String8("\nPrior client events (most recent at top):\n");
2214
2215    Mutex::Autolock l(mLogLock);
2216    for (const auto& msg : mEventLog) {
2217        result.appendFormat("  %s\n", msg.string());
2218    }
2219
2220    if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
2221        result.append("  ...\n");
2222    } else if (mEventLog.size() == 0) {
2223        result.append("  [no events yet]\n");
2224    }
2225    result.append("\n");
2226
2227    write(fd, result.string(), result.size());
2228}
2229
2230void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
2231    Mutex::Autolock al(mTorchClientMapMutex);
2232    for (size_t i = 0; i < mTorchClientMap.size(); i++) {
2233        if (mTorchClientMap[i] == who) {
2234            // turn off the torch mode that was turned on by dead client
2235            String8 cameraId = mTorchClientMap.keyAt(i);
2236            status_t res = mFlashlight->setTorchMode(cameraId, false);
2237            if (res) {
2238                ALOGE("%s: torch client died but couldn't turn off torch: "
2239                    "%s (%d)", __FUNCTION__, strerror(-res), res);
2240                return;
2241            }
2242            mTorchClientMap.removeItemsAt(i);
2243            break;
2244        }
2245    }
2246}
2247
2248/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
2249
2250    /**
2251      * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
2252      * binder driver
2253      */
2254
2255    logClientDied(getCallingPid(), String8("Binder died unexpectedly"));
2256
2257    // check torch client
2258    handleTorchClientBinderDied(who);
2259
2260    // check camera device client
2261    if(!evictClientIdByRemote(who)) {
2262        ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
2263        return;
2264    }
2265
2266    ALOGE("%s: Java client's binder died, removing it from the list of active clients",
2267            __FUNCTION__);
2268}
2269
2270void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId) {
2271    updateStatus(status, cameraId, {});
2272}
2273
2274void CameraService::updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
2275        std::initializer_list<ICameraServiceListener::Status> rejectSourceStates) {
2276    // Do not lock mServiceLock here or can get into a deadlock from
2277    // connect() -> disconnect -> updateStatus
2278
2279    auto state = getCameraState(cameraId);
2280
2281    if (state == nullptr) {
2282        ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
2283                cameraId.string());
2284        return;
2285    }
2286
2287    // Update the status for this camera state, then send the onStatusChangedCallbacks to each
2288    // of the listeners with both the mStatusStatus and mStatusListenerLock held
2289    state->updateStatus(status, cameraId, rejectSourceStates, [this]
2290            (const String8& cameraId, ICameraServiceListener::Status status) {
2291
2292            if (status != ICameraServiceListener::STATUS_ENUMERATING) {
2293                // Update torch status if it has a flash unit.
2294                Mutex::Autolock al(mTorchStatusMutex);
2295                ICameraServiceListener::TorchStatus torchStatus;
2296                if (getTorchStatusLocked(cameraId, &torchStatus) !=
2297                        NAME_NOT_FOUND) {
2298                    ICameraServiceListener::TorchStatus newTorchStatus =
2299                            status == ICameraServiceListener::STATUS_PRESENT ?
2300                            ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF :
2301                            ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
2302                    if (torchStatus != newTorchStatus) {
2303                        onTorchStatusChangedLocked(cameraId, newTorchStatus);
2304                    }
2305                }
2306            }
2307
2308            Mutex::Autolock lock(mStatusListenerLock);
2309
2310            for (auto& listener : mListenerList) {
2311                // TODO: Refactor status listeners to use strings for Camera IDs and remove this.
2312                int id = cameraIdToInt(cameraId);
2313                if (id != -1) listener->onStatusChanged(status, id);
2314            }
2315        });
2316}
2317
2318status_t CameraService::getTorchStatusLocked(
2319        const String8& cameraId,
2320        ICameraServiceListener::TorchStatus *status) const {
2321    if (!status) {
2322        return BAD_VALUE;
2323    }
2324    ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2325    if (index == NAME_NOT_FOUND) {
2326        // invalid camera ID or the camera doesn't have a flash unit
2327        return NAME_NOT_FOUND;
2328    }
2329
2330    *status = mTorchStatusMap.valueAt(index);
2331    return OK;
2332}
2333
2334status_t CameraService::setTorchStatusLocked(const String8& cameraId,
2335        ICameraServiceListener::TorchStatus status) {
2336    ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
2337    if (index == NAME_NOT_FOUND) {
2338        return BAD_VALUE;
2339    }
2340    ICameraServiceListener::TorchStatus& item =
2341            mTorchStatusMap.editValueAt(index);
2342    item = status;
2343
2344    return OK;
2345}
2346
2347}; // namespace android
2348