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