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