Android12 源码—— Camera 开机初始化(01)

  1. 初始化CameraService 在系统启动时zygote启动后会通过cameraserver.rc 文件初始化 CameraService

path:frameworks/av/camera/cameraserver/cameraserver.rc

bash 复制代码
service cameraserver /system/bin/cameraserver
    class main
    user cameraserver
    group audio camera input drmrpc
    ioprio rt 4
    writepid /dev/cpuset/camera-daemon/tasks /dev/stune/foreground/tasks
    rlimit rtprio 10 10

frameworks/av/camera/cameraserver/main_cameraserver.cpp

csharp 复制代码
int main(int argc __unused, char** argv __unused)
{
    // 省略无关代码 ....
    ALOGI("ServiceManager: %p", sm.get());
    CameraService::instantiate();
    ALOGI("ServiceManager: %p done instantiate", sm.get());
    // 省略无关代码 ....
}

上面代码可以看到调用了 CameraService::instantiate(); 创建CameraService 服务实例并添加到ServiceManager 中

下面看一下是如何将CameraService添加到ServiceManager 中的, 看一下BinderService.h 文件 frameworks/native/libs/binder/include/binder/BinderService.h

arduino 复制代码
namespace android {

template<typename SERVICE>
class BinderService
{
public:
    static status_t publish(bool allowIsolated = false,
                            int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
        sp<IServiceManager> sm(defaultServiceManager());
        return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated,dumpFlags);
    }
    // 省略无关代码 ....
    static void instantiate() { publish(); }
}; // namespace android

看到上面代码中new SERVICE() 实际是new CameraService

在看一下CameraSerice.h 部分代码 frameworks/av/services/camera/libcameraservice/CameraService.h

arduino 复制代码
class CameraService :
    public BinderService<CameraService>,
    public virtual ::android::hardware::BnCameraService,
    public virtual IBinder::DeathRecipient,
    public virtual CameraProviderManager::StatusListener
{
    static char const* getServiceName() { return "media.camera"; }
}

CameraService 继承 BinderService 并实现 getServiceName 方法。

那么CameraService 被实例的时候做了些什么, 主要是做一些初始化工作 frameworks/av/services/camera/libcameraservice/CameraService.cpp

scss 复制代码
CameraService::CameraService() :
        mEventLog(DEFAULT_EVENT_LOG_LENGTH),
        mNumberOfCameras(0),
        mSoundRef(0), mInitialized(false) {
    ALOGI("CameraService started (pid=%d)", getpid());
    mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
}

然后执行void CameraService::onFirstRef() 方法,通过CameraProviderManager加载Camera信息

ini 复制代码
// sp 第一次引用的时候会被调用
void CameraService::onFirstRef()
{
    ALOGI("CameraService process starting");

    BnCameraService::onFirstRef();
    // 省略无关代码 ....
    // 枚举camera 设备
    res = enumerateProviders();
    if (res == OK) {
        mInitialized = true;
    }

    ALOGI("CameraService pinged cameraservice proxy");
}
scss 复制代码
status_t CameraService::enumerateProviders() {
    status_t res;

    std::vector<std::string> deviceIds;
    {
        Mutex::Autolock l(mServiceLock);

        if (nullptr == mCameraProviderManager.get()) {
            // 创建 CameraProviderManager
            mCameraProviderManager = new CameraProviderManager();
            // 初始化
            res = mCameraProviderManager->initialize(this);
            if (res != OK) {
                ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
                        __FUNCTION__, strerror(-res), res);
                return res;
            }
        }

        mCameraProviderManager->setUpVendorTags();

        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);
        }
        // 获取设备 device ids
        deviceIds = mCameraProviderManager->getCameraDeviceIds();
    }


    for (auto& cameraId : deviceIds) {
        String8 id8 = String8(cameraId.c_str());
        if (getCameraState(id8) == nullptr) {
            onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
        }
    }

    return OK;
}

下面看一下CameraProviderManager.cppCameraProviderManager.h 中的initialize 实现
frameworks/av/services/camera/libcameraservice/common/CameraProviderManager.h

arduino 复制代码
// HAL 代理
static HardwareServiceInteractionProxy sHardwareServiceInteractionProxy;
status_t initialize(wp<StatusListener> listener,ServiceInteractionProxy *proxy = &sHardwareServiceInteractionProxy);

在上面代码在调用 initialize 函数时并没有给proxy 赋值,在调用函数的时候已经将sHardwareServiceInteractionProxy 赋值给 proxy 变量, 这里的 HardwareServiceInteractionProxy 是 Camera HAL 的代理,代码实现在CameraProviderManager.h 中,代码如下:

rust 复制代码
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);
    }
    virtual sp<hardware::camera::provider::V2_4::ICameraProvider> tryGetService(
            const std::string &serviceName) override {
        return hardware::camera::provider::V2_4::ICameraProvider::tryGetService(serviceName);
    }
    virtual sp<hardware::camera::provider::V2_4::ICameraProvider> getService(
            const std::string &serviceName) override {
        return hardware::camera::provider::V2_4::ICameraProvider::getService(serviceName);
    }

    virtual hardware::hidl_vec<hardware::hidl_string> listServices() override;
};

这里不深入介绍, 下面看CameraProviderManager.cppinitialize 函数

frameworks/av/services/camera/libcameraservice/common/CameraProviderManager.cpp

arduino 复制代码
status_t CameraProviderManager::initialize(wp<CameraProviderManager::StatusListener> listener,ServiceInteractionProxy* proxy) {
    std::lock_guard<std::mutex> lock(mInterfaceMutex);
    if (proxy == nullptr) {
        ALOGE("%s: No valid service interaction proxy provided", __FUNCTION__);
        return BAD_VALUE;
    }
    mListener = listener;
    mServiceProxy = proxy;
    mDeviceState = static_cast<hardware::hidl_bitfield<provider::V2_5::DeviceState>>(
        provider::V2_5::DeviceState::NORMAL);

    // Registering will trigger notifications for all already-known providers
    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;
    }

    // 遍历 Camera 信息
    for (const auto& instance : mServiceProxy->listServices()) {
        this->addProviderLocked(instance);
    }

    IPCThreadState::self()->flushCommands();

    return OK;
}

通过mServiceProxy获取到Hal 中 Camera服务的list 然后通过 addProviderLocked函数获取每个Camera 设备的信息

c 复制代码
status_t CameraProviderManager::addProviderLocked(const std::string& newProvider,
        bool preexisting) {
    // Several camera provider instances can be temporarily present.
    // Defer initialization of a new instance until the older instance is properly removed.
    auto providerInstance = newProvider + "-" + std::to_string(mProviderInstanceId);
    bool providerPresent = false;
    // 遍历已经存在的provider 并比较当前provider 是否已经创建
    for (const auto& providerInfo : mProviders) {
        if (providerInfo->mProviderName == newProvider) {
            ALOGW("%s: Camera provider HAL with name '%s' already registered",
                    __FUNCTION__, newProvider.c_str());
            if (preexisting) {
                return ALREADY_EXISTS;
            } else{
                ALOGW("%s: The new provider instance will get initialized immediately after the"
                        " currently present instance is removed!", __FUNCTION__);
                providerPresent = true;
                break;
            }
        }
    }
    // 创建 ProvideInfo  存放Camera 信息
    sp<ProviderInfo> providerInfo = new ProviderInfo(newProvider, providerInstance, this);
    if (!providerPresent) {
        // 进行初始化
        status_t res = tryToInitializeProviderLocked(newProvider, providerInfo);
        if (res != OK) {
            return res;
        }
    }
    // mProviders 是个 vector , 保存 providerInfo
    mProviders.push_back(providerInfo);
    mProviderInstanceId++;

    return OK;
}

status_t CameraProviderManager::tryToInitializeProviderLocked(
        const std::string& providerName, const sp<ProviderInfo>& providerInfo) {
    sp<provider::V2_4::ICameraProvider> interface;
    interface = mServiceProxy->tryGetService(providerName);
    if (interface == nullptr) {
        ALOGW("%s: Camera provider HAL '%s' is not actually available", __FUNCTION__,
                providerName.c_str());
        return BAD_VALUE;
    }

    return providerInfo->initialize(interface, mDeviceState);
}
相关推荐
van叶~1 小时前
仓颉语言实战——2.名字、作用域、变量、修饰符
android·java·javascript·仓颉
m0_748239331 小时前
【PHP】部署和发布PHP网站到IIS服务器
android·服务器·php
小林爱1 小时前
【Compose multiplatform教程14】【组件】LazyColumn组件
android·前端·kotlin·android studio·框架·多平台
牧杉-惊蛰2 小时前
html转PDF
android·pdf
yangfeipancc8 小时前
数据库-用户管理
android·数据库
字节流动9 小时前
Android Java 版本的 MSAA OpenGL ES 多重采样
android·java·opengles
xuanfengwuxiang9 小时前
安卓帧率获取
android·python·测试工具·adb·性能优化·pycharm
柯南二号13 小时前
Task ‘wrapper‘ not found in project ‘:example‘. 报错解决
android·gradle·hippy
我又来搬代码了13 小时前
【Android】项目升级时报错 android:style/Holo.Widget
android·gitee
洞见不一样的自己15 小时前
android 常用方法
android