android 7.1 camera service

1.服务注册的路径

./frameworks/av/camera/cameraserver/main_cameraserver.cpp

#define LOG_TAG "cameraserver"
//#define LOG_NDEBUG 0

// from LOCAL_C_INCLUDES
#include "CameraService.h"

using namespace android;

int main(int argc __unused, char** argv __unused)
{
    signal(SIGPIPE, SIG_IGN);

    sp<ProcessState> proc(ProcessState::self());
    sp<IServiceManager> sm = defaultServiceManager();
    ALOGI("ServiceManager: %p", sm.get());
    CameraService::instantiate();
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
}

//下面分析CameraService::instantiate(); 

在frameworks/av/services/camera/libcameraservice/CameraService.cpp中没有找到instantiate函数,因此我们在他们的父类看一下有没有这个方法。

先列一下CameraService 的继承类

class CameraService :
    public BinderService<CameraService>,
    public ::android::hardware::BnCameraService,
    public IBinder::DeathRecipient,
    public camera_module_callbacks_t

果不其然,我们在./frameworks/native/include/binder/BinderService.h中发现了instantiate的踪影。

template<typename SERVICE>
class BinderService
{
public:
    static status_t publish(bool allowIsolated = false) {
        sp<IServiceManager> sm(defaultServiceManager());
        return sm->addService(
                String16(SERVICE::getServiceName()),
                new SERVICE(), allowIsolated);
    }

    static void publishAndJoinThreadPool(bool allowIsolated = false) {
        publish(allowIsolated);
        joinThreadPool();
    }

    static void instantiate() { publish(); }

    static status_t shutdown() { return NO_ERROR; }

private:
    static void joinThreadPool() {
        sp<ProcessState> ps(ProcessState::self());
        ps->startThreadPool();
        ps->giveThreadPoolName();
        IPCThreadState::self()->joinThreadPool();
    }
};
我们在frameworks/av/services/camera/libcameraservice/CameraService.h中发现如下
static char const* getServiceName() { return "media.camera"; }
CameraService::instantiate();
//等价于如下
static status_t publish(bool allowIsolated = false) {
	sp<IServiceManager> sm(defaultServiceManager());
	return sm->addService("media.camera",  new CameraService(), allowIsolated);
}

//注意这里等价做了两件事情

1.先new CameraService ,调用构造函数初始化对象

2.调用addService函数将它注册到SM中

frameworks/av/services/camera/libcameraservice/CameraService.cpp

static CameraService *gCameraService;

CameraService::CameraService() :
        mEventLog(DEFAULT_EVENT_LOG_LENGTH),
        mNumberOfCameras(0), mNumberOfNormalCameras(0),
        mSoundRef(0), mModule(nullptr) {
    ALOGI("CameraService started (pid=%d)", getpid());
    gCameraService = this;

    this->camera_device_status_change = android::camera_device_status_change;
    this->torch_mode_status_change = android::torch_mode_status_change;

    mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
}

1.实际binder通信的onTransact函数实现位于ICameraService.cpp

BnCameraService::onTransact(uint32_t _aidl_code, const ::android::Parcel& _aidl_data, ::android::Parcel* _aidl_reply, uint32_t _aidl_flags)

的代码路径为:

./out/target/product/msm8953_64/obj/SHARED_LIBRARIES/libcamera_client_intermediates/aidl-generated/src/aidl/android/hardware/ICameraService.cpp

2. CameraService::onFirstRef()函数的调用时机(这里才是camera的服务的开始)

参考网址:https://blog.csdn.net/bob_fly1984/article/details/77150263

在这个incStrong函数中,主要做了三件事情:

一是增加弱引用计数    

二是增加强引用计数

 三是如果发现是首次调用这个对象的incStrong函数,就会调用一个这个对象的onFirstRef函数,让对象有机会在对象被首次引用时做一些处理逻辑

//代码路径:frameworks/native/libs/binder/Binder.cpp

BpRefBase::BpRefBase(const sp<IBinder>& o) : mRemote(o.get()), mRefs(NULL), mState(0)
//o.get(),这个是sp类的获取实际数据指针的一个方法,你只要知道它返回的是 sp<xxxx> 中 xxx* 指针就行
{
    extendObjectLifetime(OBJECT_LIFETIME_WEAK);


    if (mRemote) // mRemote 就是刚才的 BpBinder(0)
{
        mRemote->incStrong(this);           // Removed on first IncStrong(). //这个时候会去调用 onFirstRef函数
        mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.
    }
}

相应的CameraService实例里面onFirstRef()函数完成调用

下面是CameraService::onFirstRef()的部分解析

void CameraService::onFirstRef()
{
	ALOGE("CameraService process starting");

	BnCameraService::onFirstRef();

	// Update battery life tracking if service is restarting
	BatteryNotifier& notifier(BatteryNotifier::getInstance());
	notifier.noteResetCamera();
	notifier.noteResetFlashlight();
	
//1.jni 层获取 HAL 层的接口信息

	camera_module_t *rawModule;
	int err = hw_get_module(CAMERA_HARDWARE_MODULE_ID,(const hw_module_t **)&rawModule);
	if (err < 0) 
	{
		ALOGE("Could not load camera HAL module: %d (%s)", err, strerror(-err));
		logServiceError("Could not load camera HAL module", err);
		return;
	}
//2.创建一个 CameraModule 类。构造函数中将 hw_get_module 得到的 HAL_MODULE_INFO_SYM 传入到 CameraModule 中的 mModule
//	初始化 mModule 	调用 int CameraModule::init() 

	mModule = new CameraModule(rawModule);
	err = mModule->init();
	if (err != OK) 
	{
		ALOGE("Could not initialize camera HAL module: %d (%s)", err, strerror(-err));
		logServiceError("Could not initialize camera HAL module", err);

		delete mModule;
		mModule = nullptr;
		return;
	}
	ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());

//3.获取已经probe成功的camera的数量

	mNumberOfCameras = mModule->getNumberOfCameras();
	mNumberOfNormalCameras = mNumberOfCameras;

	// Setup vendor tags before we call get_camera_info the first time because HAL might need to setup static vendor keys in get_camera_info
	VendorTagDescriptor::clearGlobalVendorTagDescriptor();
	if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_2) 
	{
		setUpVendorTags();
	}

	mFlashlight = new CameraFlashlight(*mModule, *this);
	status_t res = mFlashlight->findFlashUnits();
	if (res) {
		// impossible because we haven't open any camera devices.
		ALOGE("Failed to find flash units.");
	}

	int latestStrangeCameraId = INT_MAX;
	for (int i = 0; i < mNumberOfCameras; i++) 
	{
		String8 cameraId = String8::format("%d", i);

		// Get camera info

		struct camera_info info;
		bool haveInfo = true;
//4.根据camera ID 去 得到camera的相关信息
		status_t rc = mModule->getCameraInfo(i, &info);
		if (rc != NO_ERROR) {
			ALOGE("%s: Received error loading camera info for device %d, cost and"
					" conflicting devices fields set to defaults for this device.",
					__FUNCTION__, i);
			haveInfo = false;
		}

		// Check for backwards-compatibility support
		if (haveInfo) 
		{
			if (checkCameraCapabilities(i, info, &latestStrangeCameraId) != OK) {
				delete mModule;
				mModule = nullptr;
				return;
			}
		}

		// Defaults to use for cost and conflicting devices
		int cost = 100;
		char** conflicting_devices = nullptr;
		size_t conflicting_devices_length = 0;

		// If using post-2.4 module version, query the cost + conflicting devices from the HAL
		if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && haveInfo)
		{
			cost = info.resource_cost;
			conflicting_devices = info.conflicting_devices;
			conflicting_devices_length = info.conflicting_devices_length;
		}

		std::set<String8> conflicting;
		for (size_t i = 0; i < conflicting_devices_length; i++)
		{
			conflicting.emplace(String8(conflicting_devices[i]));
		}

		// Initialize state for each camera device
		{
			Mutex::Autolock lock(mCameraStatesLock);
			mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost, conflicting));
		}

		if (mFlashlight->hasFlashUnit(cameraId)) 
		{
			mTorchStatusMap.add(cameraId, ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF);
		}
	}

	if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_1) 
	{
//5.设置回调函数
		mModule->setCallbacks(this);
	}

	CameraService::pingCameraServiceProxy();
}
/*	1.jni 层获取 HAL 层的接口信息
	代码路径:hardware/qcom/camera/QCamera2/QCamera2Hal.cpp
	hw_get_module(CAMERA_HARDWARE_MODULE_ID,(const hw_module_t **)&rawModule);
	hw_get_module 是 jni 层获取 HAL 层 module 的接口函数
	https://blog.csdn.net/computertechnology/article/details/17006107
*/


static hw_module_t camera_common = {
    .tag                    = HARDWARE_MODULE_TAG,
    .module_api_version     = CAMERA_MODULE_API_VERSION_2_4,
    .hal_api_version        = HARDWARE_HAL_API_VERSION,
    .id                     = CAMERA_HARDWARE_MODULE_ID,
    .name                   = "QCamera Module",
    .author                 = "Qualcomm Innovation Center Inc",
    .methods                = &qcamera::QCamera2Factory::mModuleMethods,
    .dso                    = NULL,
    .reserved               = {0}
};

camera_module_t HAL_MODULE_INFO_SYM = {
    .common                 = camera_common,
    .get_number_of_cameras  = qcamera::QCamera2Factory::get_number_of_cameras,
    .get_camera_info        = qcamera::QCamera2Factory::get_camera_info,
    .set_callbacks          = qcamera::QCamera2Factory::set_callbacks,
    .get_vendor_tag_ops     = qcamera::QCamera3VendorTags::get_vendor_tag_ops,
    .open_legacy            = qcamera::QCamera2Factory::open_legacy,
    .set_torch_mode         = qcamera::QCamera2Factory::set_torch_mode,
    .init                   = NULL,
    .reserved               = {0}
};



/*
    2.创建一个 CameraModule 类。构造函数中将 hw_get_module 得到的 HAL_MODULE_INFO_SYM 传入到 CameraModule 中的 mModule
    代码路径:frameworks/av/services/camera/libcameraservice/common/CameraModule.cpp
    创建一个 CameraModule 类。构造函数中将 hw_get_module 得到的 HAL_MODULE_INFO_SYM 传入到 CameraModule 中的 mModule
    mModule = new CameraModule(rawModule); //camera_module_t *rawModule;
*/

CameraModule::CameraModule(camera_module_t *module) 
{
	if (module == NULL) 
	{
		ALOGE("%s: camera hardware module must not be null", __FUNCTION__);
		assert(0);
	}
	mModule = module;
}


int CameraModule::init() 
{
    ATRACE_CALL();
    int res = OK;
    if (getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 && mModule->init != NULL)
	{
        ATRACE_BEGIN("camera_module->init");
        res = mModule->init();//init = NULL 所以这个时候没有init的操作
        ATRACE_END();
    }
    mCameraInfoMap.setCapacity(getNumberOfCameras());//这里获取的是整个的camera的数量
	//https://blog.csdn.net/JIEJINQUANIL/article/details/51166154 
    return res;
}


/*
	3.获取已经probe成功的camera的数量
	代码路径:frameworks/av/services/camera/libcameraservice/common/CameraModule.cpp
			  hardware/qcom/camera/QCamera2/QCamera2Factory.cpp
*/

int CameraModule::getNumberOfCameras() {
    int numCameras;
    ATRACE_BEGIN("camera_module->get_number_of_cameras");
    numCameras = mModule->get_number_of_cameras();
	//这里的mModule 是来自hardware/qcom/camera/QCamera2/QCamera2Hal.cpp
    ATRACE_END();
    return numCameras;
}

int QCamera2Factory::get_number_of_cameras()
{
    int numCameras = 0;

    if (!gQCamera2Factory) {
        gQCamera2Factory = new QCamera2Factory();//首先构造函数会去执行获取 mNumOfCameras 
        if (!gQCamera2Factory) {
            LOGE("Failed to allocate Camera2Factory object");
            return 0;
        }
    }
#ifdef QCAMERA_HAL1_SUPPORT
    if(gQCameraMuxer)
        numCameras = gQCameraMuxer->get_number_of_cameras();
    else
#endif
        numCameras = gQCamera2Factory->getNumberOfCameras();
		// camera数量实际是在QCamera2Factory 的初始化中 去 确定 mNumOfCameras 
		//    gQCamera2Factory = new QCamera2Factory();
		//    QCamera2Factory::QCamera2Factory(); 

    LOGH("num of cameras: %d", numCameras);
    return numCameras;
}


/*
	//4.根据camera ID 去 得到camera的相关信息
	代码路径:frameworks/av/services/camera/libcameraservice/common/CameraModule.cpp
*/
int CameraModule::getCameraInfo(int cameraId, struct camera_info *info) 
{
    ATRACE_CALL();
    Mutex::Autolock lock(mCameraInfoLock);
    if (cameraId < 0) {
        ALOGE("%s: Invalid camera ID %d", __FUNCTION__, cameraId);
        return -EINVAL;
    }

    // Only override static_camera_characteristics for API2 devices
    int apiVersion = mModule->common.module_api_version; //8953 的是 CAMERA_MODULE_API_VERSION_2_4
    if (apiVersion < CAMERA_MODULE_API_VERSION_2_0) 
	{
        int ret;
        ATRACE_BEGIN("camera_module->get_camera_info");
        ret = mModule->get_camera_info(cameraId, info);
        // Fill in this so CameraService won't be confused by
        // possibly 0 device_version
        info->device_version = CAMERA_DEVICE_API_VERSION_1_0;
        ATRACE_END();
        return ret;
    }

    ssize_t index = mCameraInfoMap.indexOfKey(cameraId);
    if (index == NAME_NOT_FOUND) 
	{
        // Get camera info from raw module and cache it
        camera_info rawInfo, cameraInfo;
        ATRACE_BEGIN("camera_module->get_camera_info");
	//通过这里调用hardware/qcom/camera/QCamera2/QCamera2Factory.cpp
        int ret = mModule->get_camera_info(cameraId, &rawInfo);
        ATRACE_END();
        if (ret != 0) {
            return ret;
        }
        int deviceVersion = rawInfo.device_version;
        if (deviceVersion < CAMERA_DEVICE_API_VERSION_3_0)
		{
            // static_camera_characteristics is invalid
            *info = rawInfo;
            return ret;
        }
        CameraMetadata m;
        m = rawInfo.static_camera_characteristics;
        deriveCameraCharacteristicsKeys(rawInfo.device_version, m);
        cameraInfo = rawInfo;
        cameraInfo.static_camera_characteristics = m.release();
        index = mCameraInfoMap.add(cameraId, cameraInfo);
    }

    assert(index != NAME_NOT_FOUND);
    // return the cached camera info
    *info = mCameraInfoMap[index];
    return OK;
}

int QCamera2Factory::get_camera_info(int camera_id, struct camera_info *info)
{
    int rc = NO_ERROR;
#ifdef QCAMERA_HAL1_SUPPORT
    if(gQCameraMuxer)
        rc = gQCameraMuxer->get_camera_info(camera_id, info);
    else
#endif
        rc =  gQCamera2Factory->getCameraInfo(camera_id, info);

    return rc;
}
//这里会根据ID 判断为 USBCamera 还是MIPI camera 来选择不同的实现方式。
int QCamera2Factory::getCameraInfo(int camera_id, struct camera_info *info)
{
	int rc;
	ALOGI("getCameraInfo camera_id==%d",camera_id);
	if(camera_id >=  mNumOfCSICamera) {
		return usbcam_get_camera_info(camera_id, info);
	}
	if (!mNumOfCameras || camera_id >= mNumOfCameras || !info || (camera_id < 0))
	{
		LOGE("Error getting camera info!! mNumOfCameras = %d," "camera_id = %d, info = %p",	 mNumOfCameras, camera_id, info);
		return -ENODEV;
	}

	if ( NULL == mHalDescriptors ) 
	{
		LOGE("Hal descriptor table is not initialized!");
		return NO_INIT;
	}

	LOGI("Camera id %d API version %d", amera_id, mHalDescriptors[camera_id].device_version);

	// Need ANDROID_FLASH_INFO_AVAILABLE property for flashlight widget to
	// work and so get the static data regardless of HAL version
	rc = QCamera3HardwareInterface::getCamInfo(	mHalDescriptors[camera_id].cameraId, info);
	if (mHalDescriptors[camera_id].device_version ==  CAMERA_DEVICE_API_VERSION_1_0)
		{
		info->device_version = CAMERA_DEVICE_API_VERSION_1_0;
	}
	return rc;
}



/*
	//5.设置回调函数
	代码路径:frameworks/av/services/camera/libcameraservice/CameraService.h
	class CameraService : public BinderService<CameraService>, public ::android::hardware::BnCameraService, public IBinder::DeathRecipient, public camera_module_callbacks_t
	hardware/qcom/camera/QCamera2/QCamera2Factory.cpp
	hardware/qcom/camera/QCamera2/util/QCameraFlash.cpp
*/
CameraService::CameraService() : mEventLog(DEFAULT_EVENT_LOG_LENGTH), mNumberOfCameras(0), mNumberOfNormalCameras(0), mSoundRef(0), mModule(nullptr) 
{
    ALOGI("CameraService started (pid=%d)", getpid());
    gCameraService = this;
	//这里填充的是mModule->setCallbacks(this); 的callbacks
    this->camera_device_status_change = android::camera_device_status_change;
    this->torch_mode_status_change = android::torch_mode_status_change;

    mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
}


参考文档:

1. Android 5.1 Camera 架构学习(一)——Camera初始化 

https://blog.csdn.net/u012248972/article/details/50763441

2.Android系统进程间通信(IPC)机制Binder中的Server启动过程源代码分析 

 https://blog.csdn.net/u012248972/article/details/50763441











猜你喜欢

转载自blog.csdn.net/huifeidedabian/article/details/80636047