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