CameraService.cpp revision cb0652e5a850b2fcd919e977247e87239efaf70e
12e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor/*
22e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * Copyright (C) 2008 The Android Open Source Project
32e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor *
42e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * Licensed under the Apache License, Version 2.0 (the "License");
52e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * you may not use this file except in compliance with the License.
62e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * You may obtain a copy of the License at
72e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor *
82e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor *      http://www.apache.org/licenses/LICENSE-2.0
92e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor *
102e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * Unless required by applicable law or agreed to in writing, software
112e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * distributed under the License is distributed on an "AS IS" BASIS,
122e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
132e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * See the License for the specific language governing permissions and
142e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor * limitations under the License.
152e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor */
162e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
172e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#define LOG_TAG "CameraService"
1850d62d1b4a98adbc83de8f8cd1379ea1c25656f7Douglas Gregor//#define LOG_NDEBUG 0
19d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor
202e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <stdio.h>
212e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <string.h>
222e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <sys/types.h>
232e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <pthread.h>
242e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
252e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <binder/AppOpsManager.h>
26011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner#include <binder/IPCThreadState.h>
27011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner#include <binder/IServiceManager.h>
283e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt#include <binder/MemoryBase.h>
29011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner#include <binder/MemoryHeapBase.h>
302e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <cutils/atomic.h>
31011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner#include <cutils/properties.h>
322a3009a432bdcec59e6383d7b2b17494d6f91649Douglas Gregor#include <gui/Surface.h>
332e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <hardware/hardware.h>
342e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <media/AudioSystem.h>
352e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <media/IMediaHTTPService.h>
362e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <media/mediaplayer.h>
372e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <utils/Errors.h>
382e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <utils/Log.h>
392e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <utils/String16.h>
402e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <utils/Trace.h>
412e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include <system/camera_vendor_tags.h>
422e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
432e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "CameraService.h"
442e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "api1/CameraClient.h"
452e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "api1/Camera2Client.h"
462e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "api_pro/ProCamera2Client.h"
472e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "api2/CameraDeviceClient.h"
482e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "utils/CameraTraces.h"
492e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#include "CameraDeviceFactory.h"
50e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor
512a3009a432bdcec59e6383d7b2b17494d6f91649Douglas Gregornamespace android {
523e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt
532a3009a432bdcec59e6383d7b2b17494d6f91649Douglas Gregor// ----------------------------------------------------------------------------
542e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor// Logging support -- this is for debugging only
552e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor// Use "adb shell dumpsys media.camera -v 1" to change it.
562e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorvolatile int32_t gLogLevel = 0;
572e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
582e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
592e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
602e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
612e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatic void setLogLevel(int level) {
622e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    android_atomic_write(level, &gLogLevel);
63e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor}
642e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
652e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor// ----------------------------------------------------------------------------
662e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
672e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatic int getCallingPid() {
682e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    return IPCThreadState::self()->getCallingPid();
692e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
702e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
712e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatic int getCallingUid() {
72e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    return IPCThreadState::self()->getCallingUid();
73e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor}
742e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
75e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregorextern "C" {
76e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregorstatic void camera_device_status_change(
77e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        const struct camera_module_callbacks* callbacks,
782e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        int camera_id,
79e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        int new_status) {
80e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    sp<CameraService> cs = const_cast<CameraService*>(
81e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor                                static_cast<const CameraService*>(callbacks));
822e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
83e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    cs->onDeviceStatusChanged(
84e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        camera_id,
85e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        new_status);
86e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor}
872e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor} // extern "C"
882e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
892e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor// ----------------------------------------------------------------------------
902e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
912e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor// This is ugly and only safe if we never re-create the CameraService, but
922e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor// should be ok for now.
932e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatic CameraService *gCameraService;
942e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
952e1cd4264d363ca869bf37ef160902f211d21b8cDouglas GregorCameraService::CameraService()
962e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    :mSoundRef(0), mModule(0)
972e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor{
98e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    ALOGI("CameraService started (pid=%d)", getpid());
992e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    gCameraService = this;
1002e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1012e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    for (size_t i = 0; i < MAX_CAMERAS; ++i) {
1022e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        mStatusList[i] = ICameraServiceListener::STATUS_PRESENT;
1032e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
1042e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1052e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    this->camera_device_status_change = android::camera_device_status_change;
1062e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
1071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1082e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorvoid CameraService::onFirstRef()
1092e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor{
110ac8d75fe94f2aefde5179d53e230b99a1fe1201aChris Lattner    LOG1("CameraService::onFirstRef");
1112e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1122e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    BnCameraService::onFirstRef();
113e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor
114e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
115e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor                (const hw_module_t **)&mModule) < 0) {
116e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        ALOGE("Could not load camera HAL module");
117ac8d75fe94f2aefde5179d53e230b99a1fe1201aChris Lattner        mNumberOfCameras = 0;
118e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    }
119e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    else {
1203e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt        ALOGI("Loaded \"%s\" camera module", mModule->common.name);
1213e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt        mNumberOfCameras = mModule->get_number_of_cameras();
1223e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt        if (mNumberOfCameras > MAX_CAMERAS) {
1233e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt            ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
1243e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt                    mNumberOfCameras, MAX_CAMERAS);
1253e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt            mNumberOfCameras = MAX_CAMERAS;
1262e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        }
1272e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        for (int i = 0; i < mNumberOfCameras; i++) {
1281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump            setCameraFree(i);
1291eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        }
1302e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
131e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        if (mModule->common.module_api_version >=
132e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor                CAMERA_MODULE_API_VERSION_2_1) {
133e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor            mModule->set_callbacks(this);
134e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        }
135e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor
1361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        VendorTagDescriptor::clearGlobalVendorTagDescriptor();
1371eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
138e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_2) {
139e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor            setUpVendorTags();
1402e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        }
1412e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1423e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt        CameraDeviceFactory::registerService(this);
1433e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    }
1443e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt}
1453e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt
1463e518bda00d710754ca077cf9be8dd821e16a854Sean HuntCameraService::~CameraService() {
1473e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    for (int i = 0; i < mNumberOfCameras; i++) {
1482e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        if (mBusy[i]) {
1492e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor            ALOGE("camera %d is still in use in destructor!", i);
1502e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        }
1512e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
1522a3009a432bdcec59e6383d7b2b17494d6f91649Douglas Gregor
1532e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    VendorTagDescriptor::clearGlobalVendorTagDescriptor();
1542def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor    gCameraService = NULL;
1552def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor}
1562def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor
1572def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregorvoid CameraService::onDeviceStatusChanged(int cameraId,
1582e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor                                          int newStatus)
1592e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor{
1602e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    ALOGI("%s: Status changed for cameraId=%d, newStatus=%d", __FUNCTION__,
1612e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor          cameraId, newStatus);
1622e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
1641eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        ALOGE("%s: Bad camera ID %d", __FUNCTION__, cameraId);
1652e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return;
1662e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
1672e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1682e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if ((int)getStatus(cameraId) == newStatus) {
1692e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("%s: State transition to the same status 0x%x not allowed",
1702e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor              __FUNCTION__, (uint32_t)newStatus);
1716ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor        return;
1726ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor    }
1736ab3524f72a6e64aa04973fa9433b5559abb3525Douglas Gregor
1742def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor    /* don't do this in updateStatus
1752def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor       since it is also called from connect and we could get into a deadlock */
1761eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (newStatus == CAMERA_DEVICE_STATUS_NOT_PRESENT) {
1771eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        Vector<sp<BasicClient> > clientsToDisconnect;
1782def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor        {
1792def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor           Mutex::Autolock al(mServiceLock);
1802def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor
18191058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner           /* Find all clients that we need to disconnect */
18291058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner           sp<BasicClient> client = mClient[cameraId].promote();
18391058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner           if (client.get() != NULL) {
18491058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner               clientsToDisconnect.push_back(client);
18591058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner           }
18691058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner
18791058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner           int i = cameraId;
18891058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner           for (size_t j = 0; j < mProClientList[i].size(); ++j) {
1891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump               sp<ProClient> cl = mProClientList[i][j].promote();
1902e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor               if (cl != NULL) {
1912e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor                   clientsToDisconnect.push_back(cl);
1921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump               }
19310bd36882406cdf4805e35add1ce2f11ab9ae152Douglas Gregor           }
19410bd36882406cdf4805e35add1ce2f11ab9ae152Douglas Gregor        }
19510bd36882406cdf4805e35add1ce2f11ab9ae152Douglas Gregor
1962e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        /* now disconnect them. don't hold the lock
1972e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor           or we can get into a deadlock */
1982e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
1991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump        for (size_t i = 0; i < clientsToDisconnect.size(); ++i) {
20091058ff73fd3b00275348dd4d49f83501dfc0542Chris Lattner            sp<BasicClient> client = clientsToDisconnect[i];
2012e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
202ac8d75fe94f2aefde5179d53e230b99a1fe1201aChris Lattner            client->disconnect();
2032e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor            /**
2042e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor             * The remote app will no longer be able to call methods on the
2052e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor             * client since the client PID will be reset to 0
2062e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor             */
2072e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        }
2082e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
20944b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor        ALOGV("%s: After unplug, disconnected %zu clients",
21044b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor              __FUNCTION__, clientsToDisconnect.size());
21144b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor    }
21244b4321feab46299d3f5cfd404680884752a0fcfDouglas Gregor
213a8f32e0965ee19ecc53cd796e34268377a20357cDouglas Gregor    updateStatus(
214a8f32e0965ee19ecc53cd796e34268377a20357cDouglas Gregor            static_cast<ICameraServiceListener::Status>(newStatus), cameraId);
215a8f32e0965ee19ecc53cd796e34268377a20357cDouglas Gregor
216a8f32e0965ee19ecc53cd796e34268377a20357cDouglas Gregor}
217a8f32e0965ee19ecc53cd796e34268377a20357cDouglas Gregor
2183e518bda00d710754ca077cf9be8dd821e16a854Sean Huntint32_t CameraService::getNumberOfCameras() {
219011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner    return mNumberOfCameras;
220011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner}
221011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner
222011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattnerstatus_t CameraService::getCameraInfo(int cameraId,
223011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner                                      struct CameraInfo* cameraInfo) {
2241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (!mModule) {
2252e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return -ENODEV;
2262e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2272e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2282e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
2292e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return BAD_VALUE;
230e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    }
231e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor
232e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    struct camera_info info;
233e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    status_t rc = mModule->get_camera_info(cameraId, &info);
234e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    cameraInfo->facing = info.facing;
2353e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    cameraInfo->orientation = info.orientation;
2363e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    return rc;
2373e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt}
2383e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt
2392e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatus_t CameraService::getCameraCharacteristics(int cameraId,
2402e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor                                                CameraMetadata* cameraInfo) {
2412e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (!cameraInfo) {
2422e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
2432def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor        return BAD_VALUE;
2442def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor    }
2452def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor
2462def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor    if (!mModule) {
2472def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor        ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
2482def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor        return -ENODEV;
2492def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor    }
2502def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor
2512def48394f6d48bde0dec2b514193c2b533265b5Douglas Gregor    if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_0) {
2522e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        // TODO: Remove this check once HAL1 shim is in place.
2532e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("%s: Only HAL module version V2 or higher supports static metadata", __FUNCTION__);
2542e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return BAD_VALUE;
2552e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2562e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2572e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
2582e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("%s: Invalid camera id: %d", __FUNCTION__, cameraId);
2592e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return BAD_VALUE;
2602e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2612e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2622e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    int facing;
2632e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (getDeviceVersion(cameraId, &facing) == CAMERA_DEVICE_API_VERSION_1_0) {
2642e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        // TODO: Remove this check once HAL1 shim is in place.
2652e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("%s: HAL1 doesn't support static metadata yet", __FUNCTION__);
2662e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return BAD_VALUE;
2672e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2682e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
26970f5bc77dbe4172bde860e15d8b3c29e0d5005cbAnders Carlsson    if (getDeviceVersion(cameraId, &facing) <= CAMERA_DEVICE_API_VERSION_2_1) {
27070f5bc77dbe4172bde860e15d8b3c29e0d5005cbAnders Carlsson        // Disable HAL2.x support for camera2 API for now.
2712e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGW("%s: HAL2.x doesn't support getCameraCharacteristics for now", __FUNCTION__);
2722e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return BAD_VALUE;
2732e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2742e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2752e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    struct camera_info info;
2762e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    status_t ret = mModule->get_camera_info(cameraId, &info);
2772e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    *cameraInfo = info.static_camera_characteristics;
2782e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2792e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    return ret;
2802e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
2812e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2822e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatus_t CameraService::getCameraVendorTagDescriptor(/*out*/sp<VendorTagDescriptor>& desc) {
2832e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (!mModule) {
2842e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("%s: camera hardware module doesn't exist", __FUNCTION__);
2852e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return -ENODEV;
2862e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2872e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2882e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (mModule->common.module_api_version < CAMERA_MODULE_API_VERSION_2_2) {
2892e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        // TODO: Remove this check once HAL1 shim is in place.
2902e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGW("%s: Only HAL module version V2.2 or higher supports vendor tags", __FUNCTION__);
2912e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return -EOPNOTSUPP;
2922e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
2932e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2942e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
2952e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    return OK;
2962e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
2972e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
2982e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorint CameraService::getDeviceVersion(int cameraId, int* facing) {
2992e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    struct camera_info info;
3002e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (mModule->get_camera_info(cameraId, &info) != OK) {
3012e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return -1;
3022e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
303e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor
3042e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    int deviceVersion;
3052e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (mModule->common.module_api_version >= CAMERA_MODULE_API_VERSION_2_0) {
3062e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        deviceVersion = info.device_version;
3072e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    } else {
3082e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
3092e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
3102e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3112e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (facing) {
3122e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        *facing = info.facing;
3132e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
314909e58988b3a3bb2ad36bec03aafa1302544fd73John McCall
3152e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    return deviceVersion;
3162e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
3172e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3182e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorbool CameraService::isValidCameraId(int cameraId) {
3192e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    int facing;
32050d62d1b4a98adbc83de8f8cd1379ea1c25656f7Douglas Gregor    int deviceVersion = getDeviceVersion(cameraId, &facing);
3212e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3222e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    switch(deviceVersion) {
3232e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor      case CAMERA_DEVICE_API_VERSION_1_0:
3242e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor      case CAMERA_DEVICE_API_VERSION_2_0:
3252e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor      case CAMERA_DEVICE_API_VERSION_2_1:
32650d62d1b4a98adbc83de8f8cd1379ea1c25656f7Douglas Gregor      case CAMERA_DEVICE_API_VERSION_3_0:
3272e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor      case CAMERA_DEVICE_API_VERSION_3_1:
3282e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor      case CAMERA_DEVICE_API_VERSION_3_2:
3292e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return true;
3302e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor      default:
3312e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return false;
33250d62d1b4a98adbc83de8f8cd1379ea1c25656f7Douglas Gregor    }
3332e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3342e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    return false;
3352e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
3362e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3372e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorbool CameraService::setUpVendorTags() {
3382e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    vendor_tag_ops_t vOps = vendor_tag_ops_t();
3391eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
34050d62d1b4a98adbc83de8f8cd1379ea1c25656f7Douglas Gregor    // Check if vendor operations have been implemented
341e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    if (mModule->get_vendor_tag_ops == NULL) {
342e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        ALOGI("%s: No vendor tags defined for this device.", __FUNCTION__);
343e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor        return false;
344e94ca9e4371c022329270436b3dd77adc4ddfa8fDouglas Gregor    }
3453e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt
3463e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
3473e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    mModule->get_vendor_tag_ops(&vOps);
3483e518bda00d710754ca077cf9be8dd821e16a854Sean Hunt    ATRACE_END();
3491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3502e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    // Ensure all vendor operations are present
351011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner    if (vOps.get_tag_count == NULL || vOps.get_all_tags == NULL ||
352011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner            vOps.get_section_name == NULL || vOps.get_tag_name == NULL ||
353011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner            vOps.get_tag_type == NULL) {
354011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner        ALOGE("%s: Vendor tag operations not fully defined. Ignoring definitions."
355011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner               , __FUNCTION__);
356011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner        return false;
357011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner    }
358011bb4edf731d529da1cbf71c7c2696aaf5a054fChris Lattner
3591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // Read all vendor tag definitions into a descriptor
360d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor    sp<VendorTagDescriptor> desc;
361d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor    status_t res;
362d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor    if ((res = VendorTagDescriptor::createDescriptorFromOps(&vOps, /*out*/desc))
363d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor            != OK) {
364d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor        ALOGE("%s: Could not generate descriptor from vendor tag operations,"
365d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor              "received error %s (%d). Camera clients will not be able to use"
366d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor              "vendor tags", __FUNCTION__, strerror(res), res);
367d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor        return false;
368d5a423b279e787e9fdd8309fe52cb515388c54eaDouglas Gregor    }
3692e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3702e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    // Set the global descriptor to use with camera metadata
3712e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    VendorTagDescriptor::setAsGlobalVendorTagDescriptor(desc);
3722e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    return true;
3732e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor}
3742e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3752e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregorstatus_t CameraService::validateConnect(int cameraId,
3762e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor                                    /*inout*/
3772e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor                                    int& clientUid) const {
3782e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3792e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    int callingPid = getCallingPid();
3802e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3812e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (clientUid == USE_CALLING_UID) {
3822e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        clientUid = getCallingUid();
3832e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    } else {
3842e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        // We only trust our own process to forward client UIDs
3852e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        if (callingPid != getpid()) {
3861eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump            ALOGE("CameraService::connect X (pid %d) rejected (don't trust clientUid)",
3872e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor                    callingPid);
3882e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor            return PERMISSION_DENIED;
3892e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        }
3902e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
3912e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
3922e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    if (!mModule) {
3932e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        ALOGE("Camera HAL module not loaded");
3942e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor        return -ENODEV;
3952e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor    }
3962e1cd4264d363ca869bf37ef160902f211d21b8cDouglas Gregor
397    if (cameraId < 0 || cameraId >= mNumberOfCameras) {
398        ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
399            callingPid, cameraId);
400        return -ENODEV;
401    }
402
403    char value[PROPERTY_VALUE_MAX];
404    property_get("sys.secpolicy.camera.disabled", value, "0");
405    if (strcmp(value, "1") == 0) {
406        // Camera is disabled by DevicePolicyManager.
407        ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
408        return -EACCES;
409    }
410
411    ICameraServiceListener::Status currentStatus = getStatus(cameraId);
412    if (currentStatus == ICameraServiceListener::STATUS_NOT_PRESENT) {
413        ALOGI("Camera is not plugged in,"
414               " connect X (pid %d) rejected", callingPid);
415        return -ENODEV;
416    } else if (currentStatus == ICameraServiceListener::STATUS_ENUMERATING) {
417        ALOGI("Camera is enumerating,"
418               " connect X (pid %d) rejected", callingPid);
419        return -EBUSY;
420    }
421    // Else don't check for STATUS_NOT_AVAILABLE.
422    //  -- It's done implicitly in canConnectUnsafe /w the mBusy array
423
424    return OK;
425}
426
427bool CameraService::canConnectUnsafe(int cameraId,
428                                     const String16& clientPackageName,
429                                     const sp<IBinder>& remoteCallback,
430                                     sp<BasicClient> &client) {
431    String8 clientName8(clientPackageName);
432    int callingPid = getCallingPid();
433
434    if (mClient[cameraId] != 0) {
435        client = mClient[cameraId].promote();
436        if (client != 0) {
437            if (remoteCallback == client->getRemote()) {
438                LOG1("CameraService::connect X (pid %d) (the same client)",
439                     callingPid);
440                return true;
441            } else {
442                // TODOSC: need to support 1 regular client,
443                // multiple shared clients here
444                ALOGW("CameraService::connect X (pid %d) rejected"
445                      " (existing client).", callingPid);
446                return false;
447            }
448        }
449        mClient[cameraId].clear();
450    }
451
452    /*
453    mBusy is set to false as the last step of the Client destructor,
454    after which it is guaranteed that the Client destructor has finished (
455    including any inherited destructors)
456
457    We only need this for a Client subclasses since we don't allow
458    multiple Clents to be opened concurrently, but multiple BasicClient
459    would be fine
460    */
461    if (mBusy[cameraId]) {
462        ALOGW("CameraService::connect X (pid %d, \"%s\") rejected"
463                " (camera %d is still busy).", callingPid,
464                clientName8.string(), cameraId);
465        return false;
466    }
467
468    return true;
469}
470
471status_t CameraService::connect(
472        const sp<ICameraClient>& cameraClient,
473        int cameraId,
474        const String16& clientPackageName,
475        int clientUid,
476        /*out*/
477        sp<ICamera>& device) {
478
479    String8 clientName8(clientPackageName);
480    int callingPid = getCallingPid();
481
482    LOG1("CameraService::connect E (pid %d \"%s\", id %d)", callingPid,
483            clientName8.string(), cameraId);
484
485    status_t status = validateConnect(cameraId, /*inout*/clientUid);
486    if (status != OK) {
487        return status;
488    }
489
490
491    sp<Client> client;
492    {
493        Mutex::Autolock lock(mServiceLock);
494        sp<BasicClient> clientTmp;
495        if (!canConnectUnsafe(cameraId, clientPackageName,
496                              cameraClient->asBinder(),
497                              /*out*/clientTmp)) {
498            return -EBUSY;
499        } else if (client.get() != NULL) {
500            device = static_cast<Client*>(clientTmp.get());
501            return OK;
502        }
503
504        int facing = -1;
505        int deviceVersion = getDeviceVersion(cameraId, &facing);
506
507        // If there are other non-exclusive users of the camera,
508        //  this will tear them down before we can reuse the camera
509        if (isValidCameraId(cameraId)) {
510            // transition from PRESENT -> NOT_AVAILABLE
511            updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
512                         cameraId);
513        }
514
515        switch(deviceVersion) {
516          case CAMERA_DEVICE_API_VERSION_1_0:
517            client = new CameraClient(this, cameraClient,
518                    clientPackageName, cameraId,
519                    facing, callingPid, clientUid, getpid());
520            break;
521          case CAMERA_DEVICE_API_VERSION_2_0:
522          case CAMERA_DEVICE_API_VERSION_2_1:
523          case CAMERA_DEVICE_API_VERSION_3_0:
524          case CAMERA_DEVICE_API_VERSION_3_1:
525          case CAMERA_DEVICE_API_VERSION_3_2:
526            client = new Camera2Client(this, cameraClient,
527                    clientPackageName, cameraId,
528                    facing, callingPid, clientUid, getpid(),
529                    deviceVersion);
530            break;
531          case -1:
532            ALOGE("Invalid camera id %d", cameraId);
533            return BAD_VALUE;
534          default:
535            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
536            return INVALID_OPERATION;
537        }
538
539        status_t status = connectFinishUnsafe(client, client->getRemote());
540        if (status != OK) {
541            // this is probably not recoverable.. maybe the client can try again
542            // OK: we can only get here if we were originally in PRESENT state
543            updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId);
544            return status;
545        }
546
547        mClient[cameraId] = client;
548        LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId,
549             getpid());
550    }
551    // important: release the mutex here so the client can call back
552    //    into the service from its destructor (can be at the end of the call)
553
554    device = client;
555    return OK;
556}
557
558status_t CameraService::connectFinishUnsafe(const sp<BasicClient>& client,
559                                            const sp<IBinder>& remoteCallback) {
560    status_t status = client->initialize(mModule);
561    if (status != OK) {
562        return status;
563    }
564
565    remoteCallback->linkToDeath(this);
566
567    return OK;
568}
569
570status_t CameraService::connectPro(
571                                        const sp<IProCameraCallbacks>& cameraCb,
572                                        int cameraId,
573                                        const String16& clientPackageName,
574                                        int clientUid,
575                                        /*out*/
576                                        sp<IProCameraUser>& device)
577{
578    String8 clientName8(clientPackageName);
579    int callingPid = getCallingPid();
580
581    LOG1("CameraService::connectPro E (pid %d \"%s\", id %d)", callingPid,
582            clientName8.string(), cameraId);
583    status_t status = validateConnect(cameraId, /*inout*/clientUid);
584    if (status != OK) {
585        return status;
586    }
587
588    sp<ProClient> client;
589    {
590        Mutex::Autolock lock(mServiceLock);
591        {
592            sp<BasicClient> client;
593            if (!canConnectUnsafe(cameraId, clientPackageName,
594                                  cameraCb->asBinder(),
595                                  /*out*/client)) {
596                return -EBUSY;
597            }
598        }
599
600        int facing = -1;
601        int deviceVersion = getDeviceVersion(cameraId, &facing);
602
603        switch(deviceVersion) {
604          case CAMERA_DEVICE_API_VERSION_1_0:
605            ALOGE("Camera id %d uses HALv1, doesn't support ProCamera",
606                  cameraId);
607            return -EOPNOTSUPP;
608            break;
609          case CAMERA_DEVICE_API_VERSION_2_0:
610          case CAMERA_DEVICE_API_VERSION_2_1:
611          case CAMERA_DEVICE_API_VERSION_3_0:
612          case CAMERA_DEVICE_API_VERSION_3_1:
613          case CAMERA_DEVICE_API_VERSION_3_2:
614            client = new ProCamera2Client(this, cameraCb, String16(),
615                    cameraId, facing, callingPid, USE_CALLING_UID, getpid());
616            break;
617          case -1:
618            ALOGE("Invalid camera id %d", cameraId);
619            return BAD_VALUE;
620          default:
621            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
622            return INVALID_OPERATION;
623        }
624
625        status_t status = connectFinishUnsafe(client, client->getRemote());
626        if (status != OK) {
627            return status;
628        }
629
630        mProClientList[cameraId].push(client);
631
632        LOG1("CameraService::connectPro X (id %d, this pid is %d)", cameraId,
633                getpid());
634    }
635    // important: release the mutex here so the client can call back
636    //    into the service from its destructor (can be at the end of the call)
637    device = client;
638    return OK;
639}
640
641status_t CameraService::connectDevice(
642        const sp<ICameraDeviceCallbacks>& cameraCb,
643        int cameraId,
644        const String16& clientPackageName,
645        int clientUid,
646        /*out*/
647        sp<ICameraDeviceUser>& device)
648{
649
650    String8 clientName8(clientPackageName);
651    int callingPid = getCallingPid();
652
653    LOG1("CameraService::connectDevice E (pid %d \"%s\", id %d)", callingPid,
654            clientName8.string(), cameraId);
655
656    status_t status = validateConnect(cameraId, /*inout*/clientUid);
657    if (status != OK) {
658        return status;
659    }
660
661    sp<CameraDeviceClient> client;
662    {
663        Mutex::Autolock lock(mServiceLock);
664        {
665            sp<BasicClient> client;
666            if (!canConnectUnsafe(cameraId, clientPackageName,
667                                  cameraCb->asBinder(),
668                                  /*out*/client)) {
669                return -EBUSY;
670            }
671        }
672
673        int facing = -1;
674        int deviceVersion = getDeviceVersion(cameraId, &facing);
675
676        // If there are other non-exclusive users of the camera,
677        //  this will tear them down before we can reuse the camera
678        if (isValidCameraId(cameraId)) {
679            // transition from PRESENT -> NOT_AVAILABLE
680            updateStatus(ICameraServiceListener::STATUS_NOT_AVAILABLE,
681                         cameraId);
682        }
683
684        switch(deviceVersion) {
685          case CAMERA_DEVICE_API_VERSION_1_0:
686            ALOGW("Camera using old HAL version: %d", deviceVersion);
687            return -EOPNOTSUPP;
688           // TODO: don't allow 2.0  Only allow 2.1 and higher
689          case CAMERA_DEVICE_API_VERSION_2_0:
690          case CAMERA_DEVICE_API_VERSION_2_1:
691          case CAMERA_DEVICE_API_VERSION_3_0:
692          case CAMERA_DEVICE_API_VERSION_3_1:
693          case CAMERA_DEVICE_API_VERSION_3_2:
694            client = new CameraDeviceClient(this, cameraCb, String16(),
695                    cameraId, facing, callingPid, USE_CALLING_UID, getpid());
696            break;
697          case -1:
698            ALOGE("Invalid camera id %d", cameraId);
699            return BAD_VALUE;
700          default:
701            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
702            return INVALID_OPERATION;
703        }
704
705        status_t status = connectFinishUnsafe(client, client->getRemote());
706        if (status != OK) {
707            // this is probably not recoverable.. maybe the client can try again
708            // OK: we can only get here if we were originally in PRESENT state
709            updateStatus(ICameraServiceListener::STATUS_PRESENT, cameraId);
710            return status;
711        }
712
713        LOG1("CameraService::connectDevice X (id %d, this pid is %d)", cameraId,
714                getpid());
715
716        mClient[cameraId] = client;
717    }
718    // important: release the mutex here so the client can call back
719    //    into the service from its destructor (can be at the end of the call)
720
721    device = client;
722    return OK;
723}
724
725
726status_t CameraService::addListener(
727                                const sp<ICameraServiceListener>& listener) {
728    ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
729
730    if (listener == 0) {
731        ALOGE("%s: Listener must not be null", __FUNCTION__);
732        return BAD_VALUE;
733    }
734
735    Mutex::Autolock lock(mServiceLock);
736
737    Vector<sp<ICameraServiceListener> >::iterator it, end;
738    for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
739        if ((*it)->asBinder() == listener->asBinder()) {
740            ALOGW("%s: Tried to add listener %p which was already subscribed",
741                  __FUNCTION__, listener.get());
742            return ALREADY_EXISTS;
743        }
744    }
745
746    mListenerList.push_back(listener);
747
748    /* Immediately signal current status to this listener only */
749    {
750        Mutex::Autolock m(mStatusMutex) ;
751        int numCams = getNumberOfCameras();
752        for (int i = 0; i < numCams; ++i) {
753            listener->onStatusChanged(mStatusList[i], i);
754        }
755    }
756
757    return OK;
758}
759status_t CameraService::removeListener(
760                                const sp<ICameraServiceListener>& listener) {
761    ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
762
763    if (listener == 0) {
764        ALOGE("%s: Listener must not be null", __FUNCTION__);
765        return BAD_VALUE;
766    }
767
768    Mutex::Autolock lock(mServiceLock);
769
770    Vector<sp<ICameraServiceListener> >::iterator it;
771    for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
772        if ((*it)->asBinder() == listener->asBinder()) {
773            mListenerList.erase(it);
774            return OK;
775        }
776    }
777
778    ALOGW("%s: Tried to remove a listener %p which was not subscribed",
779          __FUNCTION__, listener.get());
780
781    return BAD_VALUE;
782}
783
784void CameraService::removeClientByRemote(const wp<IBinder>& remoteBinder) {
785    int callingPid = getCallingPid();
786    LOG1("CameraService::removeClientByRemote E (pid %d)", callingPid);
787
788    // Declare this before the lock to make absolutely sure the
789    // destructor won't be called with the lock held.
790    Mutex::Autolock lock(mServiceLock);
791
792    int outIndex;
793    sp<BasicClient> client = findClientUnsafe(remoteBinder, outIndex);
794
795    if (client != 0) {
796        // Found our camera, clear and leave.
797        LOG1("removeClient: clear camera %d", outIndex);
798        mClient[outIndex].clear();
799
800        client->getRemote()->unlinkToDeath(this);
801    } else {
802
803        sp<ProClient> clientPro = findProClientUnsafe(remoteBinder);
804
805        if (clientPro != NULL) {
806            // Found our camera, clear and leave.
807            LOG1("removeClient: clear pro %p", clientPro.get());
808
809            clientPro->getRemoteCallback()->asBinder()->unlinkToDeath(this);
810        }
811    }
812
813    LOG1("CameraService::removeClientByRemote X (pid %d)", callingPid);
814}
815
816sp<CameraService::ProClient> CameraService::findProClientUnsafe(
817                        const wp<IBinder>& cameraCallbacksRemote)
818{
819    sp<ProClient> clientPro;
820
821    for (int i = 0; i < mNumberOfCameras; ++i) {
822        Vector<size_t> removeIdx;
823
824        for (size_t j = 0; j < mProClientList[i].size(); ++j) {
825            wp<ProClient> cl = mProClientList[i][j];
826
827            sp<ProClient> clStrong = cl.promote();
828            if (clStrong != NULL && clStrong->getRemote() == cameraCallbacksRemote) {
829                clientPro = clStrong;
830                break;
831            } else if (clStrong == NULL) {
832                // mark to clean up dead ptr
833                removeIdx.push(j);
834            }
835        }
836
837        // remove stale ptrs (in reverse so the indices dont change)
838        for (ssize_t j = (ssize_t)removeIdx.size() - 1; j >= 0; --j) {
839            mProClientList[i].removeAt(removeIdx[j]);
840        }
841
842    }
843
844    return clientPro;
845}
846
847sp<CameraService::BasicClient> CameraService::findClientUnsafe(
848                        const wp<IBinder>& cameraClient, int& outIndex) {
849    sp<BasicClient> client;
850
851    for (int i = 0; i < mNumberOfCameras; i++) {
852
853        // This happens when we have already disconnected (or this is
854        // just another unused camera).
855        if (mClient[i] == 0) continue;
856
857        // Promote mClient. It can fail if we are called from this path:
858        // Client::~Client() -> disconnect() -> removeClientByRemote().
859        client = mClient[i].promote();
860
861        // Clean up stale client entry
862        if (client == NULL) {
863            mClient[i].clear();
864            continue;
865        }
866
867        if (cameraClient == client->getRemote()) {
868            // Found our camera
869            outIndex = i;
870            return client;
871        }
872    }
873
874    outIndex = -1;
875    return NULL;
876}
877
878CameraService::BasicClient* CameraService::getClientByIdUnsafe(int cameraId) {
879    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
880    return mClient[cameraId].unsafe_get();
881}
882
883Mutex* CameraService::getClientLockById(int cameraId) {
884    if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
885    return &mClientLock[cameraId];
886}
887
888sp<CameraService::BasicClient> CameraService::getClientByRemote(
889                                const wp<IBinder>& cameraClient) {
890
891    // Declare this before the lock to make absolutely sure the
892    // destructor won't be called with the lock held.
893    sp<BasicClient> client;
894
895    Mutex::Autolock lock(mServiceLock);
896
897    int outIndex;
898    client = findClientUnsafe(cameraClient, outIndex);
899
900    return client;
901}
902
903status_t CameraService::onTransact(
904    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
905    // Permission checks
906    switch (code) {
907        case BnCameraService::CONNECT:
908        case BnCameraService::CONNECT_PRO:
909            const int pid = getCallingPid();
910            const int self_pid = getpid();
911            if (pid != self_pid) {
912                // we're called from a different process, do the real check
913                if (!checkCallingPermission(
914                        String16("android.permission.CAMERA"))) {
915                    const int uid = getCallingUid();
916                    ALOGE("Permission Denial: "
917                         "can't use the camera pid=%d, uid=%d", pid, uid);
918                    return PERMISSION_DENIED;
919                }
920            }
921            break;
922    }
923
924    return BnCameraService::onTransact(code, data, reply, flags);
925}
926
927// The reason we need this busy bit is a new CameraService::connect() request
928// may come in while the previous Client's destructor has not been run or is
929// still running. If the last strong reference of the previous Client is gone
930// but the destructor has not been finished, we should not allow the new Client
931// to be created because we need to wait for the previous Client to tear down
932// the hardware first.
933void CameraService::setCameraBusy(int cameraId) {
934    android_atomic_write(1, &mBusy[cameraId]);
935
936    ALOGV("setCameraBusy cameraId=%d", cameraId);
937}
938
939void CameraService::setCameraFree(int cameraId) {
940    android_atomic_write(0, &mBusy[cameraId]);
941
942    ALOGV("setCameraFree cameraId=%d", cameraId);
943}
944
945// We share the media players for shutter and recording sound for all clients.
946// A reference count is kept to determine when we will actually release the
947// media players.
948
949MediaPlayer* CameraService::newMediaPlayer(const char *file) {
950    MediaPlayer* mp = new MediaPlayer();
951    if (mp->setDataSource(NULL /* httpService */, file, NULL) == NO_ERROR) {
952        mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
953        mp->prepare();
954    } else {
955        ALOGE("Failed to load CameraService sounds: %s", file);
956        return NULL;
957    }
958    return mp;
959}
960
961void CameraService::loadSound() {
962    Mutex::Autolock lock(mSoundLock);
963    LOG1("CameraService::loadSound ref=%d", mSoundRef);
964    if (mSoundRef++) return;
965
966    mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
967    mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
968}
969
970void CameraService::releaseSound() {
971    Mutex::Autolock lock(mSoundLock);
972    LOG1("CameraService::releaseSound ref=%d", mSoundRef);
973    if (--mSoundRef) return;
974
975    for (int i = 0; i < NUM_SOUNDS; i++) {
976        if (mSoundPlayer[i] != 0) {
977            mSoundPlayer[i]->disconnect();
978            mSoundPlayer[i].clear();
979        }
980    }
981}
982
983void CameraService::playSound(sound_kind kind) {
984    LOG1("playSound(%d)", kind);
985    Mutex::Autolock lock(mSoundLock);
986    sp<MediaPlayer> player = mSoundPlayer[kind];
987    if (player != 0) {
988        player->seekTo(0);
989        player->start();
990    }
991}
992
993// ----------------------------------------------------------------------------
994
995CameraService::Client::Client(const sp<CameraService>& cameraService,
996        const sp<ICameraClient>& cameraClient,
997        const String16& clientPackageName,
998        int cameraId, int cameraFacing,
999        int clientPid, uid_t clientUid,
1000        int servicePid) :
1001        CameraService::BasicClient(cameraService, cameraClient->asBinder(),
1002                clientPackageName,
1003                cameraId, cameraFacing,
1004                clientPid, clientUid,
1005                servicePid)
1006{
1007    int callingPid = getCallingPid();
1008    LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
1009
1010    mRemoteCallback = cameraClient;
1011
1012    cameraService->setCameraBusy(cameraId);
1013    cameraService->loadSound();
1014
1015    LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
1016}
1017
1018// tear down the client
1019CameraService::Client::~Client() {
1020    ALOGV("~Client");
1021    mDestructionStarted = true;
1022
1023    mCameraService->releaseSound();
1024    // unconditionally disconnect. function is idempotent
1025    Client::disconnect();
1026}
1027
1028CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
1029        const sp<IBinder>& remoteCallback,
1030        const String16& clientPackageName,
1031        int cameraId, int cameraFacing,
1032        int clientPid, uid_t clientUid,
1033        int servicePid):
1034        mClientPackageName(clientPackageName)
1035{
1036    mCameraService = cameraService;
1037    mRemoteBinder = remoteCallback;
1038    mCameraId = cameraId;
1039    mCameraFacing = cameraFacing;
1040    mClientPid = clientPid;
1041    mClientUid = clientUid;
1042    mServicePid = servicePid;
1043    mOpsActive = false;
1044    mDestructionStarted = false;
1045}
1046
1047CameraService::BasicClient::~BasicClient() {
1048    ALOGV("~BasicClient");
1049    mDestructionStarted = true;
1050}
1051
1052void CameraService::BasicClient::disconnect() {
1053    ALOGV("BasicClient::disconnect");
1054    mCameraService->removeClientByRemote(mRemoteBinder);
1055    // client shouldn't be able to call into us anymore
1056    mClientPid = 0;
1057}
1058
1059status_t CameraService::BasicClient::startCameraOps() {
1060    int32_t res;
1061
1062    mOpsCallback = new OpsCallback(this);
1063
1064    {
1065        ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
1066              __FUNCTION__, String8(mClientPackageName).string(), mClientUid);
1067    }
1068
1069    mAppOpsManager.startWatchingMode(AppOpsManager::OP_CAMERA,
1070            mClientPackageName, mOpsCallback);
1071    res = mAppOpsManager.startOp(AppOpsManager::OP_CAMERA,
1072            mClientUid, mClientPackageName);
1073
1074    if (res != AppOpsManager::MODE_ALLOWED) {
1075        ALOGI("Camera %d: Access for \"%s\" has been revoked",
1076                mCameraId, String8(mClientPackageName).string());
1077        return PERMISSION_DENIED;
1078    }
1079    mOpsActive = true;
1080    return OK;
1081}
1082
1083status_t CameraService::BasicClient::finishCameraOps() {
1084    if (mOpsActive) {
1085        mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid,
1086                mClientPackageName);
1087        mOpsActive = false;
1088    }
1089    mAppOpsManager.stopWatchingMode(mOpsCallback);
1090    mOpsCallback.clear();
1091
1092    return OK;
1093}
1094
1095void CameraService::BasicClient::opChanged(int32_t op, const String16& packageName) {
1096    String8 name(packageName);
1097    String8 myName(mClientPackageName);
1098
1099    if (op != AppOpsManager::OP_CAMERA) {
1100        ALOGW("Unexpected app ops notification received: %d", op);
1101        return;
1102    }
1103
1104    int32_t res;
1105    res = mAppOpsManager.checkOp(AppOpsManager::OP_CAMERA,
1106            mClientUid, mClientPackageName);
1107    ALOGV("checkOp returns: %d, %s ", res,
1108            res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
1109            res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
1110            res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
1111            "UNKNOWN");
1112
1113    if (res != AppOpsManager::MODE_ALLOWED) {
1114        ALOGI("Camera %d: Access for \"%s\" revoked", mCameraId,
1115                myName.string());
1116        // Reset the client PID to allow server-initiated disconnect,
1117        // and to prevent further calls by client.
1118        mClientPid = getCallingPid();
1119        CaptureResultExtras resultExtras; // a dummy result (invalid)
1120        notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_SERVICE, resultExtras);
1121        disconnect();
1122    }
1123}
1124
1125// ----------------------------------------------------------------------------
1126
1127Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
1128    return gCameraService->getClientLockById((int)(intptr_t) user);
1129}
1130
1131// Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
1132// be acquired for this to be safe
1133CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
1134    BasicClient *basicClient = gCameraService->getClientByIdUnsafe((int)(intptr_t) user);
1135    // OK: only CameraClient calls this, and they already cast anyway.
1136    Client* client = static_cast<Client*>(basicClient);
1137
1138    // This could happen if the Client is in the process of shutting down (the
1139    // last strong reference is gone, but the destructor hasn't finished
1140    // stopping the hardware).
1141    if (client == NULL) return NULL;
1142
1143    // destruction already started, so should not be accessed
1144    if (client->mDestructionStarted) return NULL;
1145
1146    return client;
1147}
1148
1149void CameraService::Client::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1150        const CaptureResultExtras& resultExtras) {
1151    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1152}
1153
1154// NOTE: function is idempotent
1155void CameraService::Client::disconnect() {
1156    ALOGV("Client::disconnect");
1157    BasicClient::disconnect();
1158    mCameraService->setCameraFree(mCameraId);
1159
1160    StatusVector rejectSourceStates;
1161    rejectSourceStates.push_back(ICameraServiceListener::STATUS_NOT_PRESENT);
1162    rejectSourceStates.push_back(ICameraServiceListener::STATUS_ENUMERATING);
1163
1164    // Transition to PRESENT if the camera is not in either of above 2 states
1165    mCameraService->updateStatus(ICameraServiceListener::STATUS_PRESENT,
1166                                 mCameraId,
1167                                 &rejectSourceStates);
1168}
1169
1170CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
1171        mClient(client) {
1172}
1173
1174void CameraService::Client::OpsCallback::opChanged(int32_t op,
1175        const String16& packageName) {
1176    sp<BasicClient> client = mClient.promote();
1177    if (client != NULL) {
1178        client->opChanged(op, packageName);
1179    }
1180}
1181
1182// ----------------------------------------------------------------------------
1183//                  IProCamera
1184// ----------------------------------------------------------------------------
1185
1186CameraService::ProClient::ProClient(const sp<CameraService>& cameraService,
1187        const sp<IProCameraCallbacks>& remoteCallback,
1188        const String16& clientPackageName,
1189        int cameraId,
1190        int cameraFacing,
1191        int clientPid,
1192        uid_t clientUid,
1193        int servicePid)
1194        : CameraService::BasicClient(cameraService, remoteCallback->asBinder(),
1195                clientPackageName, cameraId, cameraFacing,
1196                clientPid,  clientUid, servicePid)
1197{
1198    mRemoteCallback = remoteCallback;
1199}
1200
1201CameraService::ProClient::~ProClient() {
1202}
1203
1204void CameraService::ProClient::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
1205        const CaptureResultExtras& resultExtras) {
1206    mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, CAMERA_ERROR_RELEASED, 0);
1207}
1208
1209// ----------------------------------------------------------------------------
1210
1211static const int kDumpLockRetries = 50;
1212static const int kDumpLockSleep = 60000;
1213
1214static bool tryLock(Mutex& mutex)
1215{
1216    bool locked = false;
1217    for (int i = 0; i < kDumpLockRetries; ++i) {
1218        if (mutex.tryLock() == NO_ERROR) {
1219            locked = true;
1220            break;
1221        }
1222        usleep(kDumpLockSleep);
1223    }
1224    return locked;
1225}
1226
1227status_t CameraService::dump(int fd, const Vector<String16>& args) {
1228    String8 result;
1229    if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
1230        result.appendFormat("Permission Denial: "
1231                "can't dump CameraService from pid=%d, uid=%d\n",
1232                getCallingPid(),
1233                getCallingUid());
1234        write(fd, result.string(), result.size());
1235    } else {
1236        bool locked = tryLock(mServiceLock);
1237        // failed to lock - CameraService is probably deadlocked
1238        if (!locked) {
1239            result.append("CameraService may be deadlocked\n");
1240            write(fd, result.string(), result.size());
1241        }
1242
1243        bool hasClient = false;
1244        if (!mModule) {
1245            result = String8::format("No camera module available!\n");
1246            write(fd, result.string(), result.size());
1247            if (locked) mServiceLock.unlock();
1248            return NO_ERROR;
1249        }
1250
1251        result = String8::format("Camera module HAL API version: 0x%x\n",
1252                mModule->common.hal_api_version);
1253        result.appendFormat("Camera module API version: 0x%x\n",
1254                mModule->common.module_api_version);
1255        result.appendFormat("Camera module name: %s\n",
1256                mModule->common.name);
1257        result.appendFormat("Camera module author: %s\n",
1258                mModule->common.author);
1259        result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
1260        write(fd, result.string(), result.size());
1261        for (int i = 0; i < mNumberOfCameras; i++) {
1262            result = String8::format("Camera %d static information:\n", i);
1263            camera_info info;
1264
1265            status_t rc = mModule->get_camera_info(i, &info);
1266            if (rc != OK) {
1267                result.appendFormat("  Error reading static information!\n");
1268                write(fd, result.string(), result.size());
1269            } else {
1270                result.appendFormat("  Facing: %s\n",
1271                        info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
1272                result.appendFormat("  Orientation: %d\n", info.orientation);
1273                int deviceVersion;
1274                if (mModule->common.module_api_version <
1275                        CAMERA_MODULE_API_VERSION_2_0) {
1276                    deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
1277                } else {
1278                    deviceVersion = info.device_version;
1279                }
1280                result.appendFormat("  Device version: 0x%x\n", deviceVersion);
1281                if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
1282                    result.appendFormat("  Device static metadata:\n");
1283                    write(fd, result.string(), result.size());
1284                    dump_indented_camera_metadata(info.static_camera_characteristics,
1285                            fd, 2, 4);
1286                } else {
1287                    write(fd, result.string(), result.size());
1288                }
1289            }
1290
1291            sp<BasicClient> client = mClient[i].promote();
1292            if (client == 0) {
1293                result = String8::format("  Device is closed, no client instance\n");
1294                write(fd, result.string(), result.size());
1295                continue;
1296            }
1297            hasClient = true;
1298            result = String8::format("  Device is open. Client instance dump:\n");
1299            write(fd, result.string(), result.size());
1300            client->dump(fd, args);
1301        }
1302        if (!hasClient) {
1303            result = String8::format("\nNo active camera clients yet.\n");
1304            write(fd, result.string(), result.size());
1305        }
1306
1307        if (locked) mServiceLock.unlock();
1308
1309        // Dump camera traces if there were any
1310        write(fd, "\n", 1);
1311        camera3::CameraTraces::dump(fd, args);
1312
1313        // change logging level
1314        int n = args.size();
1315        for (int i = 0; i + 1 < n; i++) {
1316            String16 verboseOption("-v");
1317            if (args[i] == verboseOption) {
1318                String8 levelStr(args[i+1]);
1319                int level = atoi(levelStr.string());
1320                result = String8::format("\nSetting log level to %d.\n", level);
1321                setLogLevel(level);
1322                write(fd, result.string(), result.size());
1323            }
1324        }
1325
1326    }
1327    return NO_ERROR;
1328}
1329
1330/*virtual*/void CameraService::binderDied(
1331    const wp<IBinder> &who) {
1332
1333    /**
1334      * While tempting to promote the wp<IBinder> into a sp,
1335      * it's actually not supported by the binder driver
1336      */
1337
1338    ALOGV("java clients' binder died");
1339
1340    sp<BasicClient> cameraClient = getClientByRemote(who);
1341
1342    if (cameraClient == 0) {
1343        ALOGV("java clients' binder death already cleaned up (normal case)");
1344        return;
1345    }
1346
1347    ALOGW("Disconnecting camera client %p since the binder for it "
1348          "died (this pid %d)", cameraClient.get(), getCallingPid());
1349
1350    cameraClient->disconnect();
1351
1352}
1353
1354void CameraService::updateStatus(ICameraServiceListener::Status status,
1355                                 int32_t cameraId,
1356                                 const StatusVector *rejectSourceStates) {
1357    // do not lock mServiceLock here or can get into a deadlock from
1358    //  connect() -> ProClient::disconnect -> updateStatus
1359    Mutex::Autolock lock(mStatusMutex);
1360
1361    ICameraServiceListener::Status oldStatus = mStatusList[cameraId];
1362
1363    mStatusList[cameraId] = status;
1364
1365    if (oldStatus != status) {
1366        ALOGV("%s: Status has changed for camera ID %d from 0x%x to 0x%x",
1367              __FUNCTION__, cameraId, (uint32_t)oldStatus, (uint32_t)status);
1368
1369        if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
1370            (status != ICameraServiceListener::STATUS_PRESENT &&
1371             status != ICameraServiceListener::STATUS_ENUMERATING)) {
1372
1373            ALOGW("%s: From NOT_PRESENT can only transition into PRESENT"
1374                  " or ENUMERATING", __FUNCTION__);
1375            mStatusList[cameraId] = oldStatus;
1376            return;
1377        }
1378
1379        if (rejectSourceStates != NULL) {
1380            const StatusVector &rejectList = *rejectSourceStates;
1381            StatusVector::const_iterator it = rejectList.begin();
1382
1383            /**
1384             * Sometimes we want to conditionally do a transition.
1385             * For example if a client disconnects, we want to go to PRESENT
1386             * only if we weren't already in NOT_PRESENT or ENUMERATING.
1387             */
1388            for (; it != rejectList.end(); ++it) {
1389                if (oldStatus == *it) {
1390                    ALOGV("%s: Rejecting status transition for Camera ID %d, "
1391                          " since the source state was was in one of the bad "
1392                          " states.", __FUNCTION__, cameraId);
1393                    mStatusList[cameraId] = oldStatus;
1394                    return;
1395                }
1396            }
1397        }
1398
1399        /**
1400          * ProClients lose their exclusive lock.
1401          * - Done before the CameraClient can initialize the HAL device,
1402          *   since we want to be able to close it before they get to initialize
1403          */
1404        if (status == ICameraServiceListener::STATUS_NOT_AVAILABLE) {
1405            Vector<wp<ProClient> > proClients(mProClientList[cameraId]);
1406            Vector<wp<ProClient> >::const_iterator it;
1407
1408            for (it = proClients.begin(); it != proClients.end(); ++it) {
1409                sp<ProClient> proCl = it->promote();
1410                if (proCl.get() != NULL) {
1411                    proCl->onExclusiveLockStolen();
1412                }
1413            }
1414        }
1415
1416        Vector<sp<ICameraServiceListener> >::const_iterator it;
1417        for (it = mListenerList.begin(); it != mListenerList.end(); ++it) {
1418            (*it)->onStatusChanged(status, cameraId);
1419        }
1420    }
1421}
1422
1423ICameraServiceListener::Status CameraService::getStatus(int cameraId) const {
1424    if (cameraId < 0 || cameraId >= MAX_CAMERAS) {
1425        ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId);
1426        return ICameraServiceListener::STATUS_UNKNOWN;
1427    }
1428
1429    Mutex::Autolock al(mStatusMutex);
1430    return mStatusList[cameraId];
1431}
1432
1433}; // namespace android
1434