美文网首页
CameraService启动流程分析

CameraService启动流程分析

作者: 我和你说过 | 来源:发表于2021-08-26 15:21 被阅读0次
    image.png
    CS进程的类图.png CS进程启动流程时序图.png

    CameraService进程的启动流程

    CameraService和上层APP是通过IPC机制进行通信的,这里会用到aidl - cpp(AIDL文件会编译生成native binder所需的c文件--IXXX.h BpXXX.cpp BnXXX.cpp以及java层所需的 IXXX.java文件)这里CameraService是ICameraService.aidl 的服务端,framwork中android.hardware.camera2下面提供的CameraManager就是ICameraService.adil 的客户端代理。

    AIDL文件 服务端 客户端 BinderName
    ICameraService.aidl CameraService进程(CameraService.cpp) CameraManager(Framework API) media.camera
    ICameraServiceProxy.aidl CameraServiceProxy(Java层的系统服务) CameraService进程中使用 media.camera.proxy
    ICameraDeviceCallbacks.aidl CameraDeviceImpl.CameraDeviceCallbacks CameraService进程中使用 匿名Binder
    ICameraDeviceUser.aidl CameraService进程(CameraDeviceClient.cpp) ICameraDeviceUserWrapper(API) 匿名Binder

    1、程序的入口

    frameworks\av\camera\cameraserver\main_cameraserver.cpp

    int main(int argc __unused, char** argv __unused)
    {
        signal(SIGPIPE, SIG_IGN);
        // Set 3 threads for HIDL calls
        hardware::configureRpcThreadpool(3, /*willjoin*/ false);
        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里面

    2、开始ICameraService服务端Binder的创建和注册流程

    class CameraService :
        public BinderService<CameraService>, //模板类 主要是封装了将Binder 添加到ServiceManager进程中
        public virtual ::android::hardware::BnCameraService, // ICameraService的服务端需要继承BnCameraService(native binder的写法)
        public virtual IBinder::DeathRecipient,  //Binder死亡监听  监听客户端进程的死亡情况
        public virtual CameraProviderManager::StatusListener{}
    
    
    // CameraService::instantiate(); 调用这里的instantiate()  主要是向sm注册了ICameraService的服务端binder
    template<typename SERVICE>
    class BinderService
    {
    public:
        static status_t publish(bool allowIsolated = false,int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
            sp<IServiceManager> sm(defaultServiceManager());
            // 这里就是向sm进程中注册Binder  这里的Binder的名称是 "media.camera"
            return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated,dumpFlags);
        }
        static void publishAndJoinThreadPool(bool allowIsolated = false,int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
            publish(allowIsolated, dumpFlags);
            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();
        }
    };
    

    上面的new SERVIDE() 让程序流程来到了CameraService() 构造函数里面,CameraService继承额BnCameraService(这个是AIDL--cpp生成的代码)所以CameraService.cpp是ICameraService.adil的IPC机制的服务端。

    3 CameraService的构造函数

    CameraService::CameraService() :
            mEventLog(DEFAULT_EVENT_LOG_LENGTH), //初始化用来打印Log的圆形Buffer的长度-100
            mNumberOfCameras(0),//初始化Camera的数量为0
            mSoundRef(0), 
            mInitialized(false) //标识CameraService 是否被初始化了
    {
        ALOGI("CameraService started (pid=%d)", getpid());
        mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
    }
    

    构造函数执行完成之后,sm里面也注册了该服务的binder。然后因为CamerService继承了RefBase所以CamerService对象在第一次被创建的时候会调用到onFirstRef()函数:

    4、CameraService的onFirstRef()

    void CameraService::onFirstRef()
    {
        ALOGI("CameraService process starting");
        BnCameraService::onFirstRef(); // 调用它的父类的onFirstRef()函数
        // Update battery life tracking if service is restarting
        BatteryNotifier& notifier(BatteryNotifier::getInstance());
        notifier.noteResetCamera();
        notifier.noteResetFlashlight();
        status_t res = INVALID_OPERATION;
        //主要是调用 enumerateProviders() 函数获取CameraProvider信息。
        res = enumerateProviders();
        if (res == OK) {
            mInitialized = true;
        }
        //连接CameraServiceProxy服务,也就是"media.camera.proxy"服务,此服务由SystemServer注册到ServiceManager中
        CameraService::pingCameraServiceProxy();
        mUidPolicy = new UidPolicy(this);
        mUidPolicy->registerSelf();
    }
    

    前面主要是和电源相关的一些信息,这里不做分析。最主要的是在这里调用到了enumerateProviders()函数里面,所以

    5、CameraService::enumerateProviders()

    status_t CameraService::enumerateProviders() {
        status_t res;
        std::vector<std::string> deviceIds;
        {
            Mutex::Autolock l(mServiceLock);
            //这里就是对mCameraProviderManager创建然后调用它的初始化函数
            if (nullptr == mCameraProviderManager.get()) { 
                 // 创建一个 CameraProviderManager 对象之后调用 initialize(),
                 // 其实就是将CameraService设置为 CameraProviderManager 的监听者  
                mCameraProviderManager = new CameraProviderManager();
                // 传入的参数是 this 指针,指向当前 CameraService 实例的地址
                res = mCameraProviderManager->initialize(this); 
                if (res != OK) {
                    ALOGE("%s: Unable to initialize camera provider manager: %s (%d)" __FUNCTION__, strerror(-res), res);
                    return res;
                }
            }
            // 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
            // TODO: maybe put this into CameraProviderManager::initialize()?
            mCameraProviderManager->setUpVendorTags();
            //创建mFlashlight对象
            if (nullptr == mFlashlight.get()) {
                mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
            }
            res = mFlashlight->findFlashUnits();
            if (res != OK) {
                ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
            }
            //获取摄像头设备ID的向量集合
            deviceIds = mCameraProviderManager->getCameraDeviceIds();
        }
    
    
        for (auto& cameraId : deviceIds) {
            String8 id8 = String8(cameraId.c_str());
            onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
        }
    
        return OK;
    }
    

    上面创建了一个CameraProviderManager对象并将对象保存在CameraService中mCameraProviderManager 。继续执行 mCameraProviderManager->initialize(this)。这里的this指向的就是当前的CameraService对象(因为CameraService继承了CameraProviderManager::StatusListener)这里可以通过这个StatusListener将信息从CameraProviderManager中回调给CameraService。

    6、CameraProviderManager创建和初始化

    // CameraProviderManager::StatusListener
    struct StatusListener : virtual public RefBase {
          ~StatusListener() {}
          //  摄像头设备的状态发生
          virtual void onDeviceStatusChanged(const String8 &cameraId, hardware::camera::common::V1_0::CameraDeviceStatus newStatus) = 0;
          // 手电筒状态发生变化
          virtual void onTorchStatusChanged(const String8 &cameraId, hardware::camera::common::V1_0::TorchModeStatus newStatus) = 0;
          virtual void onNewProviderRegistered() = 0;
    };
    
    //第二个参数就是远程代理类。这个参数已经是默认赋值了,实际类HardwareServiceInteractionProxy
    status_t CameraProviderManager::initialize(wp<CameraProviderManager::StatusListener> listener,
            ServiceInteractionProxy* proxy) //proxy---HardwareServiceInteractionProxy 
    { 
        std::lock_guard<std::mutex> lock(mInterfaceMutex);
        if (proxy == nullptr) {
            ALOGE("%s: No valid service interaction proxy provided", __FUNCTION__);
            return BAD_VALUE;
        }
        mListener = listener;  //mListener的实现是在CameraService中(类似java中的回调机制)
        mServiceProxy = proxy;
        // 这里调用到CameraProviderAll.cpp 里面 然后调用到了defaultServiceManager()->registerForNotifications(),
        // 从notification 是android::hidl::manager::V1_0::IServiceNotification来看应该是老API的兼容处理
        bool success = mServiceProxy->registerForNotifications(/* instance name, empty means no filter */ "", this);
        if (!success) {
            ALOGE("%s: Unable to register with hardware service manager for notifications "
                    "about camera providers", __FUNCTION__);
            return INVALID_OPERATION;
        }
    
        // 这里主要是和CameraProvider和ExternalCameraProvider建立联系,并把对应的代理(Interface)保存到ProviderInfo中
        // 所以这两个方法执行完成之后这里有两个ProviderInfo对象(保存在mProviders中)。
        addProviderLocked(kLegacyProviderName, /*expected*/ false); //"legacy/0"
        addProviderLocked(kExternalProviderName, /*expected*/ false); //"external/0"
        return OK;
    }
    

    将传递过来的StatusListener 赋值给mListener。然后执行到 addProviderLocked(kLegacyProviderName, /expected/ false);这里传递的两个name分别是const std::string kLegacyProviderName("legacy/0"); const std::string kExternalProviderName("external/0"); 这里的name和之前分析CameraProvider进程启动的时候注册的Binder服务的名称对应上了。然后继续分析:

    7、CameraProviderManager::addProviderLocked() 和CameraProvider进程建立联系

     // 首先通过getService方法获取ICameraProvider代理。
     // 随后实例化了一个ProviderInfo对象,之后调用其initialize方法进行初始化。
     // 最后将ProviderInfo加入到一个内部容器中进行管理。
    status_t CameraProviderManager::addProviderLocked(const std::string& newProvider, bool expected) {
        //检查已知的 Provider 中是否已有名为 legacy/0 的 
        for (const auto& providerInfo : mProviders) {
            if (providerInfo->mProviderName == newProvider) {
                ALOGW("%s: Camera provider HAL with name '%s' already registered",__FUNCTION__,newProvider.c_str());
                return ALREADY_EXISTS;
            }
        }
        //这里是通过服务端Binder的名字来获取hal的ICameraProvider对象
        sp<provider::V2_4::ICameraProvider> interface;  //HIDL的服务端对象
       // 这里的mServiceProxy就是HardwareServiceInteractionProxy 
        interface = mServiceProxy->getService(newProvider);
        if (interface == nullptr) {
            if (expected) {
                ALOGE("%s: Camera provider HAL '%s' is not actually available", __FUNCTION__,newProvider.c_str());
                return BAD_VALUE;
            } else {
                return OK;
            }
        }
    
        //通过ProviderInfo保存得到的CameraHal进程的代理对象ICameraProvider
        sp<ProviderInfo> providerInfo =
                new ProviderInfo(newProvider, interface, this);
        status_t res = providerInfo->initialize();
        if (res != OK) {
            return res;
        }
    
        //将providerInfo添加到一个内部容器进行管理
        mProviders.push_back(providerInfo);
    
        return OK;
    }
    

    首先mServiceProxy->getService(newProvider)这个mServiceProxy就是HardwareServiceInteractionProxy对象。这里会调用到ICameraProvider::getService(serviceName)。

    7.1、获取CameraProvider的代理对象

    struct HardwareServiceInteractionProxy : public ServiceInteractionProxy {
            virtual bool registerForNotifications(const std::string &serviceName,
                    const sp<hidl::manager::V1_0::IServiceNotification>&notification) override {
                return hardware::camera::provider::V2_4::ICameraProvider::registerForNotifications(
                        serviceName, notification);
            }
           //这里的ICameraProvider对象就是ICameraProvider.hal 文件生成的ICameraProvider.h里面去
            virtual sp<hardware::camera::provider::V2_4::ICameraProvider> getService(
                    const std::string &serviceName) override {
                return hardware::camera::provider::V2_4::ICameraProvider::getService(serviceName);
            }
        };
    
    //ICameraProvider.h 是编译生成的文件
    //out\soong.intermediates\hardware\interfaces\camera\provider\2.4\android.hardware.camera.provider@2.4_genc++_header\gen\android\hardware\camera\provider\2.4
    static ::android::sp<ICameraProvider> getService(const std::string &serviceName="default", bool getStub=false);
    
    ##ICameraProvider.h 是头文件它cpp文件就是CameraProviderAll.cpp(它还是BpHwCameraProvider.h  BnHwCameraProvider.h的cpp文件 )
    // 这个函数返回的是BpHwCameraProvider  BpHwCameraProvider是继承的ICameraProvider
    ::android::sp<ICameraProvider> ICameraProvider::getService(const std::string &serviceName, const bool getStub) {
        return ::android::hardware::details::getServiceInternal<BpHwCameraProvider>(serviceName, true, getStub);
    }
    
    
    ##继续会调用到HidlTransportSupport.h中的getServiceInternal()函数
    ##  system/libhidl/transport/include/hidl/HidlTransportSupport.h
    template <typename BpType, typename IType = typename BpType::Pure,
              typename = std::enable_if_t<std::is_same<i_tag, typename IType::_hidl_tag>::value>,
              typename = std::enable_if_t<std::is_same<bphw_tag, typename BpType::_hidl_tag>::value>>
    // instatnce  这里是传递来的 "legacy/0"  或者 "external/0"  retry--true getStub--false
    sp<IType> getServiceInternal(const std::string& instance, bool retry, bool getStub) {
        using ::android::hidl::base::V1_0::IBase;
        //IType::descriptor --- ICameraProvider::descriptor("android.hardware.camera.provider@2.4::ICameraProvider")
        sp<IBase> base = getRawServiceInternal(IType::descriptor, instance, retry, getStub);
        if (base == nullptr) {
            return nullptr;
        }
        if (base->isRemote()) {
            // getRawServiceInternal guarantees we get the proper class
            return sp<IType>(new BpType(toBinder<IBase>(base)));
        }
        return IType::castFrom(base);
    }
    

    上面代码中执行到getRawServiceInternal(IType::descriptor, instance, retry, getStub)这里会接着调用到ServiceManagement.cpp里面去

    sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,const std::string& instance,bool retry, bool getStub) {
        using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
        using ::android::hidl::base::V1_0::IBase;
        using ::android::hidl::manager::V1_0::IServiceManager;
        sp<Waiter> waiter;
        // 获取 hwservicemanager 服务, 用于获取Service的client端即BpXXX代理类
        const sp<IServiceManager1_1> sm = defaultServiceManager1_1();
        if (sm == nullptr) {
            ALOGE("getService: defaultServiceManager() is null");
            return nullptr;
        }
        Return<Transport> transportRet = sm->getTransport(descriptor, instance);
        if (!transportRet.isOk()) {
            ALOGE("getService: defaultServiceManager()->getTransport returns %s",transportRet.description().c_str());
            return nullptr;
        }
        Transport transport = transportRet;
        const bool vintfHwbinder = (transport == Transport::HWBINDER);
        const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
    
        ........
        // 从CameraService过来的getStub  为false  会走到这个分支来。获取 cameraprovider时,
       // 拿到<sp<IBase>>,之后会New BpHwCameraProvider, 通过 BpHwCameraProvider类调用HIDL通信
        for (int tries = 0; !getStub && (vintfHwbinder || vintfLegacy); tries++) {
            if (waiter == nullptr && tries > 0) {
                waiter = new Waiter(descriptor, instance, sm);
            }
            if (waiter != nullptr) {
                waiter->reset();  // don't reorder this -- see comments on reset()
            }
            //调用 ServiceManager::get()  返回的是 CameraProvider 代理类(BpHwCameraProvider)
            Return<sp<IBase>> ret = sm->get(descriptor, instance);
            if (!ret.isOk()) {
                ALOGE("getService: defaultServiceManager()->get returns %s for %s/%s.", ret.description().c_str(), descriptor.c_str(), instance.c_str());
                break;
            }
            sp<IBase> base = ret;  //ICameraProvider是IBase的子类
            if (base != nullptr) {
                Return<bool> canCastRet =details::canCastInterface(base.get(), descriptor.c_str(), true /* emitError */);
                if (canCastRet.isOk() && canCastRet) {
                    if (waiter != nullptr) { waiter->done(); }
                    return base; // still needs to be wrapped by Bp class.
                }
                if (!handleCastError(canCastRet, descriptor, instance)) break;
            }
    
            // In case of legacy or we were not asked to retry, don't.
            if (vintfLegacy || !retry) break;
            if (waiter != nullptr) {
                ALOGI("getService: Trying again for %s/%s...", descriptor.c_str(), instance.c_str());
                waiter->wait(true /* timeout */);
            }
        }
        if (waiter != nullptr) {
            waiter->done();
        }
         // getStub 为true  也就是之前的CameraProvider启动时走的流程用于服务启动
        if (getStub || vintfPassthru || vintfLegacy) {
            const sp<IServiceManager> pm = getPassthroughServiceManager();
            if (pm != nullptr) {
                sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
                if (!getStub || trebleTestingOverride) {
                    base = wrapPassthrough(base);
                }
                return base;
            }
        }
        return nullptr;
    }
    

    上面代码首先就是获取hwservicemanager 对象。然后 hwservicemanager.get()函数从该服务中获取CameraProvider进程的代理。 Return<sp<IBase>> ret = sm->get(descriptor, instance)这里返回的BpCameraProvider继承了ICameraProvider而后者继承了IBase。这里获取CameraProvider服务端的代码到此就结束了。在CameraService进程中也可以根据获取的代理和CameraProvider进程进行数据传输。

    7、保存CameraProvider服务端的代理BpHwCameraProvider

    前面获取到的Interface(BpHWCameraProvider)会被保存在新建的一个ProviderInfo对象中,然后调用ProviderInfo::initialize()进行一些初始化。初始化完成过后,会将该providerInfo 对象存储在全局变量mProviders中。下面看看初始化中做了哪些操作

    status_t CameraProviderManager::ProviderInfo::initialize() {
        status_t res = parseProviderName(mProviderName, &mType, &mId);
        if (res != OK) {
            ALOGE("%s: Invalid provider name, ignoring", __FUNCTION__);
            return BAD_VALUE;
        }
        ALOGI("Connecting to new camera provider: %s, isRemote? %d",mProviderName.c_str(), mInterface->isRemote());
         // mInterface是在ProviderInfo的构造函数中赋值的,也就是上面获取到的BpHwCameraProvider
        // ProviderInfo实现了ICameraProviderCallback接口,所以紧接着调用了ICameraProvider的setCallback将自身注册到Camera Provider中,
        // 接收来自CameraProvider进程的事件回调。
        hardware::Return<Status> status = mInterface->setCallback(this);
        if (!status.isOk()) {
            ALOGE("%s: Transaction error setting up callbacks with camera provider '%s': %s",__FUNCTION__, mProviderName.c_str(), status.description().c_str());
            return DEAD_OBJECT;
        }
        if (status != Status::OK) {
            ALOGE("%s: Unable to register callbacks with camera provider '%s'",  __FUNCTION__, mProviderName.c_str());
            return mapToStatusT(status);
        }
        //设置死亡监听
        hardware::Return<bool> linked = mInterface->linkToDeath(this, /*cookie*/ mId);
        if (!linked.isOk()) {
            ALOGE("%s: Transaction error in linking to camera provider '%s' death: %s",__FUNCTION__, mProviderName.c_str(), linked.description().c_str());
            return DEAD_OBJECT;
        } else if (!linked) {
            ALOGW("%s: Unable to link to provider '%s' death notifications", __FUNCTION__, mProviderName.c_str());
        }
    
        // 可用摄像头列表  里面存放的是CameraId
        std::vector<std::string> devices;
        //getCameraIdList()参数是一个回调函数,等着Provider进程回调过来准备按来接收数据。主要是将状态OK的摄像的id存取到devices列表里面
        hardware::Return<void> ret = mInterface->getCameraIdList([&status, &devices]
                (Status idStatus,const hardware::hidl_vec<hardware::hidl_string>& cameraDeviceNames) {
                    status = idStatus;
                    if (status == Status::OK) {
                         for (size_t i = 0; i < cameraDeviceNames.size(); i++) {
                             devices.push_back(cameraDeviceNames[i]);
                         }
                    } 
                });
        if (!ret.isOk()) {
            ALOGE("%s: Transaction error in getting camera ID list from provider '%s': %s", __FUNCTION__, mProviderName.c_str(), linked.description().c_str());
            return DEAD_OBJECT;
        }
        if (status != Status::OK) {
            ALOGE("%s: Unable to query for camera devices from provider '%s'", __FUNCTION__, mProviderName.c_str());
            return mapToStatusT(status);
        }
    
        sp<StatusListener> listener = mManager->getStatusListener(); //好像是多余的代码
        for (auto& device : devices) { //遍历Provider进程给过来的摄像头设备名称列表
            std::string id;
            // 将设备名和状态(在这里初始成PRESENT状态)保存起来
            status_t res = addDevice(device, hardware::camera::common::V1_0::CameraDeviceStatus::PRESENT, &id);
            if (res != OK) {
                ALOGE("%s: Unable to enumerate camera device '%s': %s (%d)",  __FUNCTION__, device.c_str(), strerror(-res), res);
                continue;
            }
        }
        ALOGI("Camera provider %s ready with %zu camera devices",mProviderName.c_str(), mDevices.size());
        mInitialized = true; //标识是否初始化了
        return OK;
    }
    

    mInterface->setCallback(this) 这个会调用到CameraProvider里面去,然后这里的this是因为ProviderInfo继承了hardware::camera::provider::V2_4::ICameraProviderCallback(这里ProviderInfo是ICameraProviderCallback的匿名Binder的服务端)。CameraProvider可以通过ICameraProviderCallback传递消息到CameraService进程的ProviderInfo中。mInterface->getCameraIdList() 这是主动调用获取摄像头列表,这里是通过函数回调形式传递数据。得到摄像头名称的列表之后,就对这个列表进行遍历,根据摄像头的name属性获取摄像头的基本信息并保存起来。

    8、 保存ProviderInfo初始化时获取摄像头的名称信息

    上面的代码会继续走到 addDevice(device, hardware::camera::common::V1_0::CameraDeviceStatus::PRESENT, &id)

    status_t CameraProviderManager::ProviderInfo::addDevice(const std::string& name,CameraDeviceStatus initialStatus, /*out*/ std::string* parsedId) {
        ALOGI("Enumerating new camera device: %s", name.c_str());
        uint16_t major, minor;
        std::string type, id;
        // 将传递过来的name(设备名)解析 得到major  minor  type  id等值
       // name--"device@3.4/internal/1"  majo--3  minor--4 type--"internal" id-- 1
        status_t res = parseDeviceName(name, &major, &minor, &type, &id);
        if (res != OK) {
            return res;
        }
        if (type != mType) {
            ALOGE("%s: Device type %s does not match provider type %s", __FUNCTION__,type.c_str(), mType.c_str());
            return BAD_VALUE;
        }
        if (mManager->isValidDeviceLocked(id, major)) { //检查摄像头设备是否已经添加了ProviderInfo->mDevices中
            ALOGE("%s: Device %s: ID %s is already in use for device major version %d", __FUNCTION__,name.c_str(), id.c_str(), major);
            return BAD_VALUE;
        }
        std::unique_ptr<DeviceInfo> deviceInfo;
        switch (major) {  //这里我们分析的是Camera2的API,所以是3这个分支
            case 1:
                deviceInfo = initializeDeviceInfo<DeviceInfo1>(name, mProviderTagid,  id, minor);
                break;
            case 3: 
                //根据上面的信息去创建一个DeviceInfo3的对象
                deviceInfo = initializeDeviceInfo<DeviceInfo3>(name, mProviderTagid, id, minor);
                break;
            default:
                ALOGE("%s: Device %s: Unknown HIDL device HAL major version %d:", __FUNCTION__,name.c_str(), major);
                return BAD_VALUE;
        }
        if (deviceInfo == nullptr) return BAD_VALUE;
        deviceInfo->mStatus = initialStatus;// 将传递过来的CameraDeviceStatus::PRESENT状态赋值给创建的DeviceInfo对象
        bool isAPI1Compatible = deviceInfo->isAPI1Compatible();
        mDevices.push_back(std::move(deviceInfo));// 将创建的DeviceInfo对象保存到ProviderInfo的mDevices中
        mUniqueCameraIds.insert(id); //将CameraId存放到mUniqueCameraIds
        if (isAPI1Compatible) { //这个表明该摄像头设备支持camera api1
            mUniqueAPI1CompatibleCameraIds.push_back(id);
        }
        if (parsedId != nullptr) {
            *parsedId = id;
        }
        return OK;
    }
    

    根据摄像头的设备名称信息获取到摄像头的major minor type id等值后做了一些基本的校验,然后根据这些信息调用initializeDeviceInfo<DeviceInfo3>(name, mProviderTagid, id, minor) 创建一个DeviceInfo3对象

    9、CameraProviderManager::ProviderInfo::initializeDeviceInfo() 创建DeviceInfo3对象

     //DeviceInfoT DeviceInfo3
    template<class DeviceInfoT>
    std::unique_ptr<CameraProviderManager::ProviderInfo::DeviceInfo> CameraProviderManager::ProviderInfo::initializeDeviceInfo(
            const std::string &name, const metadata_vendor_id_t tagId,
            const std::string &id, uint16_t minorVersion) const {
        Status status;
        // DeviceInfo3 中 typedef hardware::camera::device::V3_2::ICameraDevice InterfaceT;
        // cameraInterface -- ICameDevice的代理和provider进程来通信  这里的模板是device::V3_2::ICameraDevice在Provider进程中的device/3.2/ICameraDevice.hal 
        auto cameraInterface = getDeviceInterface<typename DeviceInfoT::InterfaceT>(name);
        if (cameraInterface == nullptr) return nullptr;
        CameraResourceCost resourceCost;
        //调用到provider进程中的CameraDevice 然后通过回调接收数据
        cameraInterface->getResourceCost([&status, &resourceCost]
               ( Status s, CameraResourceCost cost) {
                    status = s;
                    resourceCost = cost;
                });
        if (status != Status::OK) {
            ALOGE("%s: Unable to obtain resource costs for camera device %s: %s", __FUNCTION__,
                    name.c_str(), statusToString(status));
            return nullptr;
        }
        for (auto& conflictName : resourceCost.conflictingDevices) {
            uint16_t major, minor;
            std::string type, id;
            status_t res = parseDeviceName(conflictName, &major, &minor, &type, &id);
            if (res != OK) {
                ALOGE("%s: Failed to parse conflicting device %s", __FUNCTION__, conflictName.c_str());
                return nullptr;
            }
            conflictName = id;
        }
        return std::unique_ptr<DeviceInfo>(new DeviceInfoT(name, tagId, id, minorVersion, resourceCost,cameraInterface));
    }
    

    获取CameraProvider进程中的的ICameraDevice.hal的代理--cameraInterface,这里的 getDeviceInterface<typename DeviceInfoT::InterfaceT>(name)函数中的模板是hardware::camera::device::V3_2::ICameraDevice所以会调用到对应版的函数如下:
    然后通过cameraInterface->getResourceCost()获取摄像头设备的一些属性信息(也就是前面CameraProvider进程中的camera_info)。

    9.1、首先看看如何得到ICameraDevice的代理

    ICameraDevice.hal 会生成ICameraDevice.h 文件

    template<>
    sp<device::V3_2::ICameraDevice>
    CameraProviderManager::ProviderInfo::getDeviceInterface <device::V3_2::ICameraDevice>(const std::string &name) const {
        Status status;
        sp<device::V3_2::ICameraDevice> cameraInterface;
        hardware::Return<void> ret;
        //这里主要是调用CameraProvider中的getCameraDeviceInterface_V3_x(name)函数 这里的name 就是前面获取到的设备名称
        ret = mInterface->getCameraDeviceInterface_V3_x(name, [&status, &cameraInterface](
            Status s, sp<device::V3_2::ICameraDevice> interface) {
                    status = s;
                    cameraInterface = interface;
                });
        if (!ret.isOk()) {
            ALOGE("%s: Transaction error trying to obtain interface for camera device %s: %s", __FUNCTION__, name.c_str(), ret.description().c_str());
            return nullptr;
        }
        if (status != Status::OK) {
            ALOGE("%s: Unable to obtain interface for camera device %s: %s", __FUNCTION__, name.c_str(), statusToString(status));
            return nullptr;
        }
        return cameraInterface; // 返回Provider进程中ICameraDevice的代理 
    }
    

    这个主要是用到了前面获取到的ICameraProvider的代理(mInterface)之后调用其getCameraDeviceInterface_V3_x(name)函数,然后通过回调的形式收到ICameraDevice的代理(可以看出这里也使用到了匿名Binder)。

    9.2、CameraProvider::getCameraDeviceInterface_V3_x(name)。

    //cameraDeviceName --  "device@3.4/internal/1"
    Return<void> CameraProvider::getCameraDeviceInterface_V3_x(const hidl_string& cameraDeviceName, getCameraDeviceInterface_V3_x_cb _hidl_cb)  {
        std::string cameraId, deviceVersion;
        bool match = matchDeviceName(cameraDeviceName, &deviceVersion, &cameraId); //根据deviceName从中获取version和cameraId的值
        if (!match) { // 判断传递过来的CameraDeviceName是否能和本地的正则表达式匹配
            _hidl_cb(Status::ILLEGAL_ARGUMENT, nullptr);
            return Void();
        }
        std::string deviceName(cameraDeviceName.c_str());
        ssize_t index = mCameraDeviceNames.indexOf(std::make_pair(cameraId, deviceName));
        if (index == NAME_NOT_FOUND) { // Either an illegal name or a device version mismatch
            Status status = Status::OK;
            ssize_t idx = mCameraIds.indexOf(cameraId);
            if (idx == NAME_NOT_FOUND) {
                ALOGE("%s: cannot find camera %s!", __FUNCTION__, cameraId.c_str());
                status = Status::ILLEGAL_ARGUMENT;
            } else { // invalid version
                ALOGE("%s: camera device %s does not support version %s!", __FUNCTION__, cameraId.c_str(), deviceVersion.c_str());
                status = Status::OPERATION_NOT_SUPPORTED;
            }
            _hidl_cb(status, nullptr);
            return Void();
        }
        if (mCameraStatusMap.count(cameraId) == 0 || mCameraStatusMap[cameraId] != CAMERA_DEVICE_STATUS_PRESENT) {
            _hidl_cb(Status::ILLEGAL_ARGUMENT, nullptr);
            return Void();
        }
        sp<android::hardware::camera::device::V3_2::ICameraDevice> device;
        if (deviceVersion == kHAL3_4) {  // kHAL3_4 == 3.4  所以流程会走到这里面来
            ALOGV("Constructing v3.4 camera device");
            // 这里会创建ICameraDevice.hal 的服务端的对象,并将mModule 传递给这个对象(CameraDevice)
           // 这里的mModule对象就是CameraModule 这个对象里面有一个camera_module_t 用来调用CameraHAL.so来操作摄像头
            sp<android::hardware::camera::device::V3_2::implementation::CameraDevice> deviceImpl =
                new android::hardware::camera::device::V3_4::implementation::CameraDevice(mModule, cameraId, mCameraDeviceNames);
            if (deviceImpl == nullptr || deviceImpl->isInitFailed()) {
                ALOGE("%s: camera device %s init failed!", __FUNCTION__, cameraId.c_str());
                device = nullptr;
                _hidl_cb(Status::INTERNAL_ERROR, nullptr);
                return Void();
            }
    
            device = deviceImpl;
            _hidl_cb (Status::OK, device);
            return Void();
        }
    
        // Since some Treble HAL revisions can map to the same legacy HAL version(s), we default
        // to the newest possible Treble HAL revision, but allow for override if needed via
        // system property.
        switch (mPreferredHal3MinorVersion) {
            case 2: { // Map legacy camera device v3 HAL to Treble camera device HAL v3.2
                ALOGV("Constructing v3.2 camera device");
                sp<android::hardware::camera::device::V3_2::implementation::CameraDevice> deviceImpl =
                        new android::hardware::camera::device::V3_2::implementation::CameraDevice(
                        mModule, cameraId, mCameraDeviceNames);
                if (deviceImpl == nullptr || deviceImpl->isInitFailed()) {
                    ALOGE("%s: camera device %s init failed!", __FUNCTION__, cameraId.c_str());
                    device = nullptr;
                    _hidl_cb(Status::INTERNAL_ERROR, nullptr);
                    return Void();
                }
                device = deviceImpl;
                break;
            }
            case 3: { // Map legacy camera device v3 HAL to Treble camera device HAL v3.3
                ALOGV("Constructing v3.3 camera device");
                sp<android::hardware::camera::device::V3_2::implementation::CameraDevice> deviceImpl =
                        new android::hardware::camera::device::V3_3::implementation::CameraDevice(
                        mModule, cameraId, mCameraDeviceNames);
                if (deviceImpl == nullptr || deviceImpl->isInitFailed()) {
                    ALOGE("%s: camera device %s init failed!", __FUNCTION__, cameraId.c_str());
                    device = nullptr;
                    _hidl_cb(Status::INTERNAL_ERROR, nullptr);
                    return Void();
                }
                device = deviceImpl;
                break;
            }
            default:
                ALOGE("%s: Unknown HAL minor version %d!", __FUNCTION__, mPreferredHal3MinorVersion);
                device = nullptr;
                _hidl_cb(Status::INTERNAL_ERROR, nullptr);
                return Void();
        }
        _hidl_cb (Status::OK, device);
        return Void();
    }
    

    在initializeDeviceInfo() 中 cameraInterface->getResourceCost()会调用到CameraProvider进程中的CameraDevice.cpp里面

    总结

    到此CameraService进程的启动流程就分析完了。大致总结一下这个启动流程做了什么:
    1、创建了一个CameraProviderManager对象来负责管理和CP进程的IPC。
    2、在CameraProviderManager里面会创建一个ProviderInfo对象来保存和CP进程通信的ICameraProvider.hal的代理。
    3、通过ICameraProvider获取摄像头的数量,然后遍历摄像头个数,通过调用ICameraProvider中的getCameraDeviceInterface_V3_x()函数创建ICameraDevice的服务端实例,并将其代理作为参数来创建DeviceInfo3对象
    CameraService 1 --- 1 CameraProviderManager 1 --- 1 ProviderInfo 1 --- M DeviceInfo3
    其中ProviderInfo 持有CP进程中CameraProvider的代理
    DeviceInfo3 持有CP进程中的CameraDevice的代理

    相关文章

      网友评论

          本文标题:CameraService启动流程分析

          本文链接:https://www.haomeiwen.com/subject/tgjmvltx.html