Camera源码分析(一)--CameraService与CameraProvider的联系

Camera源码分析(一)--CameraService与CameraProvider的联系,第1张

有参考:

作者:StoneDemo 原文:https://blog.csdn.net/qq_16775897/article/details/81240600简书: 作者:JeffMony Android Camera原理之camera provider启动 原文: https://www.jianshu.com/p/5758f14f924e简书: 作者:JeffMony Android Camera原理之cameraserver与cameraprovider是怎样联系的 原文:https://www.jianshu.com/p/6dc1ef6df400
————————————————

文章目录 Camera源码分析(一)CameraService和CameraProvider的联系1、CameraProvider启动流程概览2、CameraProvider启动2.1、CameraProvider() 分析2.2、 initialize()分析 3、CameraServer的启动与初始化3.1、CameraService::instantiate()分析3.2、enumerateProviders()分析3.3 providerInfo->initialize(interface, mDeviceState)分析

Camera源码分析(一) CameraService和CameraProvider的联系 1、CameraProvider启动流程概览

​ 系统启动时就会启动CameraProvider服务。它将Camera HAL从cameraserver进程中分离出来,作为一个独立进程 android.hardware.camera.provider@2.5-service 来控制 HAL。这两个进程之间通过HIDL机制进行通信。

​ 这样的改动源自于Android O版本加入了Treble机制,它的主要功能(如下图所示)是将services和HAL隔离,以方便HAL部分进行独立升级。这其实和APP与Framework之前的Binder机制类似,通过引入一个进程间通信机制而针对不同层级进行解耦(从Local call变成了Remote call)。

CameraProvider 执行文件对应的源码为:android/hardware/interfaces/camera/provider/2.5/default/android.hardware.camera.provider@2.5-service.rc

service vendor.camera-provider-2-5 /vendor/bin/hw/android.hardware.camera.provider@2.5-service
    interface android.hardware.camera.provider@2.5::ICameraProvider legacy/0
    interface android.hardware.camera.provider@2.4::ICameraProvider legacy/0
    class hal
    user cameraserver
    group audio camera input drmrpc
    ioprio rt 4
    capabilities SYS_NICE
    task_profiles CameraServiceCapacity MaxPerformance

cameraserver 执行文件对应的源码为:android/frameworks/av/camera/cameraserver/cameraserver.rc

service cameraserver /system/bin/cameraserver
    class main
    user cameraserver
    group audio camera input drmrpc
    ioprio rt 4
    task_profiles CameraServiceCapacity MaxPerformance
    rlimit rtprio 10 10

cameraserver 与 provider这两个进程启动、初始化的调用逻辑如下图:

由上图可见:

cameraserver一侧,CameraService类依旧是主体,通过CameraProviderManager来管理对CameraProvider的 *** 作。此处初始化的最终目的是连接上CameraProvider。

provider一侧,最终主体是CameraProvider。初始化最终目的是得到一个mModule,通过它可以直接与HAL接口定义层进行交互。

2、CameraProvider启动

android/hardware/interfaces/camera/provider/2.5/default/service.cpp

int main()
{
    using namespace android::hardware::camera::provider::V2_5::implementation;

    ALOGI("CameraProvider@2.5 legacy service is starting.");
	// 设置 当前进程用于 hwbinder 通信的最大线程数,HWBINDER_THREAD_COUNT = 6
    ::android::hardware::configureRpcThreadpool(/*threads*/ HWBINDER_THREAD_COUNT, /*willJoin*/ true);
	// 创建provider的实现,后边详细分析
    ::android::sp<ICameraProvider> provider = new CameraProvider<LegacyCameraProviderImpl_2_5>();

    status_t status;
    // kLazyService = false
    if (kLazyService) {
        auto serviceRegistrar = ::android::hardware::LazyServiceRegistrar::getInstance();
        status = serviceRegistrar.registerService(provider, "legacy/0");
    } else {
        // 注册服务到hwservicemanager
        status = provider->registerAsService("legacy/0");
    }
    LOG_ALWAYS_FATAL_IF(status != android::OK, "Error while registering provider service: %d",status);

    ::android::hardware::joinRpcThreadpool();

    return 0;
}
2.1、CameraProvider() 分析

先看下CameraProvider的构造函数:

template<typename IMPL>
struct CameraProvider : public ICameraProvider {
    CameraProvider() : impl() {}
	......
}

调用了impl也就是LegacyCameraProviderImpl_2_5的构造。

LegacyCameraProviderImpl_2_5::LegacyCameraProviderImpl_2_5() :
        LegacyCameraProviderImpl_2_4() {
}

LegacyCameraProviderImpl_2_4::LegacyCameraProviderImpl_2_4() :
        camera_module_callbacks_t({sCameraDeviceStatusChange,
                                   sTorchModeStatusChange}) {
    mInitFailed = initialize();
}

camera_module_callbacks_t是HAL的回调函数,用于通知frameworks相机状态更新。先看下LegacyCameraProviderImpl_2_4的类的申明和sCameraDeviceStatusChange/sTorchModeStatusChange函数定义,搞明白它。

struct LegacyCameraProviderImpl_2_4 : public camera_module_callbacks_t {
	......
	// static callback forwarding methods
    static void sCameraDeviceStatusChange(
        const struct camera_module_callbacks* callbacks,
        int camera_id,
        int new_status);
    static void sTorchModeStatusChange(
        const struct camera_module_callbacks* callbacks,
        const char* camera_id,
        int new_status);
	......
}

LegacyCameraProviderImpl_2_4是继承了camera_module_callbacks_t,所以类构造的同时使用sCameraDeviceStatusChange/sTorchModeStatusChange初始化了camera_module_callbacks_t中的camera_device_status_change/torch_mode_status_change函数指针。
camera_module_callbacks_t结构定义如下:android/hardware/libhardware/include/hardware/camera_common.h

typedef struct camera_module_callbacks {
    void (*camera_device_status_change)(const struct camera_module_callbacks*,
            int camera_id,
            int new_status);

    void (*torch_mode_status_change)(const struct camera_module_callbacks*,
            const char* camera_id,
            int new_status);
} camera_module_callbacks_t;

再继续往下看,调用mInitFailed = initialize();的实现

2.2、 initialize()分析
bool LegacyCameraProviderImpl_2_4::initialize() {
    camera_module_t *rawModule;
    // a  CAMERA_HARDWARE_MODULE_ID = "camera"
    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));
        return true;
    }
	// b rawModule指向HAL_MODULE_INFO_SYM结构体
    mModule = new CameraModule(rawModule);
    // c 初始化CameraModule
    err = mModule->init();
    if (err != OK) {
        ALOGE("Could not initialize camera HAL module: %d (%s)", err, strerror(-err));
        mModule.clear();
        return true;
    }
    ALOGI("Loaded \"%s\" camera module", mModule->getModuleName());

    // Setup vendor tags here so HAL can setup vendor keys in camera characteristics
    VendorTagDescriptor::clearGlobalVendorTagDescriptor();
    if (!setUpVendorTags()) {
        ALOGE("%s: Vendor tag setup failed, will not be available.", __FUNCTION__);
    }

    // Setup callback now because we are going to try openLegacy next
    err = mModule->setCallbacks(this);
    if (err != OK) {
        ALOGE("Could not set camera module callback: %d (%s)", err, strerror(-err));
        mModule.clear();
        return true;
    }
	// 属性没有赋值,因此默认是3
    mPreferredHal3MinorVersion =
        property_get_int32("ro.vendor.camera.wrapper.hal3TrebleMinorVersion", 3);
    ALOGV("Preferred HAL 3 minor version is %d", mPreferredHal3MinorVersion);
    switch(mPreferredHal3MinorVersion) {
        case 2:
        case 3:
            // OK
            break;
        default:
            ALOGW("Unknown minor camera device HAL version %d in property "
                    "'camera.wrapper.hal3TrebleMinorVersion', defaulting to 3",
                    mPreferredHal3MinorVersion);
            mPreferredHal3MinorVersion = 3;
    }
	// 获取Camera Number
    mNumberOfLegacyCameras = mModule->getNumberOfCameras();
    for (int i = 0; i < mNumberOfLegacyCameras; i++) {
        struct camera_info info;
        // 获取Camera info信息
        auto rc = mModule->getCameraInfo(i, &info);
        if (rc != NO_ERROR) {
            ALOGE("%s: Camera info query failed!", __func__);
            mModule.clear();
            return true;
        }

        if (checkCameraVersion(i, info) != OK) {
            ALOGE("%s: Camera version check failed!", __func__);
            mModule.clear();
            return true;
        }
		// 保存Camera ID和状态
        char cameraId[kMaxCameraIdLen];
        snprintf(cameraId, sizeof(cameraId), "%d", i);
        std::string cameraIdStr(cameraId);
        mCameraStatusMap[cameraIdStr] = CAMERA_DEVICE_STATUS_PRESENT;
		// 保存Camera ID和deviceNamePair,并尝试openLegacy,平台没有,不做分析。
        addDeviceNames(i);
    }

    return false; // mInitFailed
}

a、hw_get_module函数:android/hardware/libhardware/hardware.c

int hw_get_module(const char *id, const struct hw_module_t **module)
{
    return hw_get_module_by_class(id, NULL, module);
}

int hw_get_module_by_class(const char *class_id, const char *inst,
                           const struct hw_module_t **module)
{
    int i = 0;
    char prop[PATH_MAX] = {0};
    char path[PATH_MAX] = {0};
    char name[PATH_MAX] = {0};
    char prop_name[PATH_MAX] = {0};


    if (inst)
        snprintf(name, PATH_MAX, "%s.%s", class_id, inst);
    else
        // class_id = "camera"
        strlcpy(name, class_id, PATH_MAX);

    /*
     * Here we rely on the fact that calling dlopen multiple times on
     * the same .so will simply increment a refcount (and not load
     * a new copy of the library).
     * We also assume that dlopen() is thread-safe.
     */

    /* First try a property specific to the class and possibly instance */
    // 这里的属性是ro.hardware.camera,平台没有定义这个属性
    snprintf(prop_name, sizeof(prop_name), "ro.hardware.%s", name);
    if (property_get(prop_name, prop, NULL) > 0) {
        if (hw_module_exists(path, sizeof(path), name, prop) == 0) {
            goto found;
        }
    }

    /* Loop through the configuration variants looking for a module */
    for (i=0 ; i<HAL_VARIANT_KEYS_COUNT; i++) {
        if (property_get(variant_keys[i], prop, NULL) == 0) {
            continue;
        }
        if (hw_module_exists(path, sizeof(path), name, prop) == 0) {
            goto found;
        }
    }

    /* Nothing found, try the default */
    if (hw_module_exists(path, sizeof(path), name, "default") == 0) {
        goto found;
    }

    return -ENOENT;

found:
    /* load the module, if this fails, we're doomed, and we should not try
     * to load a different variant. */
    return load(class_id, path, module);
}

static int hw_module_exists(char *path, size_t path_len, const char *name,
                            const char *subname)
{
    // name: camera  subname: amlogic
    /*
    HAL_LIBRARY_PATH3:
        #define HAL_LIBRARY_PATH3 "/odm/lib64/hw"
		#define HAL_LIBRARY_PATH3 "/odm/lib/hw"
	*/
    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH3, name, subname);
    if (path_in_path(path, HAL_LIBRARY_PATH3) && access(path, R_OK) == 0)
        return 0;

    /*
    HAL_LIBRARY_PATH2:
		#define HAL_LIBRARY_PATH2 "/vendor/lib64/hw"
		#define HAL_LIBRARY_PATH2 "/vendor/lib/hw"
	*/
    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH2, name, subname);
    if (path_in_path(path, HAL_LIBRARY_PATH2) && access(path, R_OK) == 0)
        return 0;

#ifndef __ANDROID_VNDK__
    /*
    HAL_LIBRARY_PATH1:
		#define HAL_LIBRARY_PATH1 "/system/lib64/hw"
		#define HAL_LIBRARY_PATH1 "/system/lib/hw"
	*/
    snprintf(path, path_len, "%s/%s.%s.so",
             HAL_LIBRARY_PATH1, name, subname);
    if (path_in_path(path, HAL_LIBRARY_PATH1) && access(path, R_OK) == 0)
        return 0;
#endif

    return -ENOENT;
}

static const char *variant_keys[] = {
    // 平台这个值是amlogic
    "ro.hardware",  /* This goes first so that it can pick up a different
                       file on the emulator. */
    "ro.product.board",
    "ro.board.platform",
    "ro.arch"
};

hw_get_module会调用hw_get_moudle_by_class去找到实现HAL的so,class_id的值就是camera。先get ro.hardware.camera的值,这是没有的。接下来就是根据variant_keys的数组查找对应的属性值。AML的平台ro.hardware的值是amlogic,可以拿到值,就继续调用hw_module_exists函数。平台这里是在vendor下边,camera.amlogic.so,在hw_module_exists函数第二个if判断找到。

如果遍历了variant_keys这数组还是没有找到,就会调用hw_module_exists拼接camera.default.so去odm/vendor/system去找。camera.default.so的源码在hardware/libhardware/modules/camera/3_0目录下,平台方会自己实现camera.xxx.so,所以这里可以看成谷歌写的一个demo,如果自己想写一个camera HAL的话,可以参考着写。

再继续看hw_get_module_by_class,通过hw_module_exists拿到全路径之后,继续调用load。

/**
 * Load the file defined by the variant and if successful
 * return the dlopen handle and the hmi.
 * @return 0 = success, !0 = failure.
 */
static int load(const char *id,
        const char *path,
        const struct hw_module_t **pHmi)
{
    int status = -EINVAL;
    void *handle = NULL;
    struct hw_module_t *hmi = NULL;
#ifdef __ANDROID_VNDK__
    const bool try_system = false;
#else
    const bool try_system = true;
#endif

    /*
     * load the symbols resolving undefined symbols before
     * dlopen returns. Since RTLD_GLOBAL is not or'd in with
     * RTLD_NOW the external symbols will not be global
     */
    if (try_system &&
        strncmp(path, HAL_LIBRARY_PATH1, strlen(HAL_LIBRARY_PATH1)) == 0) {
        /* If the library is in system partition, no need to check
         * sphal namespace. Open it with dlopen.
         */
        handle = dlopen(path, RTLD_NOW);
    } else {
#if defined(__ANDROID_RECOVERY__)
        handle = dlopen(path, RTLD_NOW);
#else
        handle = android_load_sphal_library(path, RTLD_NOW);
#endif
    }
    if (handle == NULL) {
        char const *err_str = dlerror();
        ALOGE("load: module=%s\n%s", path, err_str?err_str:"unknown");
        status = -EINVAL;
        goto done;
    }

    /* Get the address of the struct hal_module_info. */
    //  #define HAL_MODULE_INFO_SYM_AS_STR "HMI" ??
    const char *sym = HAL_MODULE_INFO_SYM_AS_STR;
    hmi = (struct hw_module_t *)dlsym(handle, sym);
    if (hmi == NULL) {
        ALOGE("load: couldn't find symbol %s", sym);
        status = -EINVAL;
        goto done;
    }

    /* Check that the id matches */
    if (strcmp(id, hmi->id) != 0) {
        ALOGE("load: id=%s != hmi->id=%s", id, hmi->id);
        status = -EINVAL;
        goto done;
    }

    hmi->dso = handle;

    /* success */
    status = 0;

    done:
    if (status != 0) {
        hmi = NULL;
        if (handle != NULL) {
            dlclose(handle);
            handle = NULL;
        }
    } else {
        ALOGV("loaded HAL id=%s path=%s hmi=%p handle=%p",
                id, path, hmi, handle);
    }

    *pHmi = hmi;

    return status;
}

load函数会根据上面传过来的地址通过dlopen或者是android_load_sphal_library打开so。因为平台的so是在vendor下边,所以这里使用的是android_load_sphal_library函数。然后在通过HAL_MODULE_INFO_SYM_AS_STR找到对应用的符号链接。而 HAL_MODULE_INFO_SYM_AS_STR 在android/hardware/libhardware/include/hardware/hardware.h中定义的一个字符串, dlsym通过字符串去寻找与该字符串相同名字的结构体。

/**
 * Name of the hal_module_info
 */
#define HAL_MODULE_INFO_SYM         HMI

/**
 * Name of the hal_module_info as a string
 */
#define HAL_MODULE_INFO_SYM_AS_STR  "HMI"

这里我们就去平台代码里边找HAL_MODULE_INFO_SYM。

android/hardware/amlogic/camera/v3/EmulatedCameraHal.cpp

#include "EmulatedCameraFactory.h"

/*
 * Required HAL header.
 */
camera_module_t HAL_MODULE_INFO_SYM = {
    .common = {
         .tag = HARDWARE_MODULE_TAG,
         .module_api_version = CAMERA_MODULE_API_VERSION_2_2,
         .hal_api_version = HARDWARE_HAL_API_VERSION,
         .id = CAMERA_HARDWARE_MODULE_ID,
         .name = "Camera Module",
         .author = "The Multi-media team from Amlogic SH.",
         .methods = &android::EmulatedCameraFactory::mCameraModuleMethods,
         .dso = NULL,
         .reserved = {0},
    },
    .get_number_of_cameras = android::EmulatedCameraFactory::get_number_of_cameras,
    .get_camera_info = android::EmulatedCameraFactory::get_camera_info,
    .set_callbacks = android::EmulatedCameraFactory::set_callbacks,
    .get_vendor_tag_ops = android::EmulatedCameraFactory::get_vendor_tag_ops,
};

到这里基本就明白了hal库是怎么加载上了。hw_get_module拿到的rawModule二维指针指向的就是HAL_MODULE_INFO_SYM这个结构体。

b、new CameraModule(rawModule)分析

android/hardware/interfaces/camera/common/1.0/default/CameraModule.cpp

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

就是将module的值保存起来。

c、mModule->init()分析

int CameraModule::init() {
    ATRACE_CALL();
    int res = OK;
    // 因为没有init,所以这个判断不成立
    if (getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4 &&
            mModule->init != NULL) {
        ATRACE_BEGIN("camera_module->init");
        res = mModule->init();
        ATRACE_END();
    }
    // 获取Camera Number
    mNumberOfCameras = getNumberOfCameras();
    mCameraInfoMap.setCapacity(mNumberOfCameras);
    return res;
}
3、CameraServer的启动与初始化

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

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

    // Set 5 threads for HIDL calls. Now cameraserver will serve HIDL calls in
    // addition to consuming them from the Camera HAL as well.
    // 用于设置 当前进程用于hwbinder通信的最大线程数
    hardware::configureRpcThreadpool(5, /*willjoin*/ false);

    sp<ProcessState> proc(ProcessState::self());
    sp<IServiceManager> sm = defaultServiceManager();
    ALOGI("ServiceManager: %p", sm.get());
    // 初始化CameraService服务
    CameraService::instantiate(); 
    ALOGI("ServiceManager: %p done instantiate", sm.get());
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
}
3.1、CameraService::instantiate()分析

instantiate接口并不是定义在CameraService中,而是定义在BinderService类中。

static void instantiate() { 
    publish(); 
}

static status_t publish(bool allowIsolated = false,
                        int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT) {
    // 获取IServiceManager服务的代理对象BpServiceManager
    sp<IServiceManager> sm(defaultServiceManager());
    //注册服务SERVICE为CameraService
    return sm->addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated, dumpFlags);
}

status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
                                        bool allowIsolated, int dumpsysPriority)
{
    Status status = mTheRealServiceManager->addService(
        String8(name).c_str(), service, allowIsolated, dumpsysPriority);
    return status.exceptionCode();
}

addService的 第二个参数 const sp& service传入的参数是CameraService对象,会自动调用sp的自动类型转换

android/system/core/libutils/include/utils/StrongPointer.h

template<typename T> template<typename U>
sp<T>::sp(const sp<U>& other)
        : m_ptr(other.m_ptr) {
    if (m_ptr)
        m_ptr->incStrong(this);
}

inStrong 会触发 onFirstRef方法

void RefBase::incStrong(const void* id) const
{
    weakref_impl* const refs = mRefs;
    refs->incWeak(id);
    
    refs->addStrongRef(id);
    const int32_t c = refs->mStrong.fetch_add(1, std::memory_order_relaxed);
    ALOG_ASSERT(c > 0, "incStrong() called on %p after last strong ref", refs);
#if PRINT_REFS
    ALOGD("incStrong of %p from %p: cnt=%d\n", this, id, c);
#endif
    if (c != INITIAL_STRONG_VALUE)  {
        return;
    }

    int32_t old __unused = refs->mStrong.fetch_sub(INITIAL_STRONG_VALUE, std::memory_order_relaxed);
    // A decStrong() must still happen after us.
    ALOG_ASSERT(old > INITIAL_STRONG_VALUE, "0x%x too small", old);
    //触发onFirstRef方法
    refs->mBase->onFirstRef();
}

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

void CameraService::onFirstRef()
{
    ......
    res = enumerateProviders();
    if (res == OK) {
        mInitialized = true;
    }
	......
}

这里主要看enumerateProviders这个函数

3.2、enumerateProviders()分析

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

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;
            }
        }
		......
    }
	......

    return OK;
}

这里主要看initialize函数,先看它的声明:

/android/frameworks/av/services/camera/libcameraservice/common/CameraProviderManager.h

/**
 * Initialize the manager and give it a status listener; optionally accepts a service
 * interaction proxy.
 *
 * The default proxy communicates via the hardware service manager; alternate proxies can be
 * used for testing. The lifetime of the proxy must exceed the lifetime of the manager.
 */
status_t initialize(wp<StatusListener> listener,
        ServiceInteractionProxy *proxy = &sHardwareServiceInteractionProxy);
用于初始化管理器,并给它设置一个状态监听(即CameraService实例)。选择性地接受一个与服务交互的代理默认的代理通过HardWare服务管理器进行通信。备用的代理可以用来进行测试。代理的生命周期必须要超过管理器的生命周期。注意到在enumerateProviders中调用该接口时,只有一个入参,说明当前用的是默认代理

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

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;
    }

    // listServices调用其 listManifestByInterface(…) 从清单文件中检索provider::V2_4::ICameraProvider::descriptor这个描述符对应的服务
    // 遍历所有的代理服务, 其实就是provider::V2_4::ICameraProvider注册服务
    for (const auto& instance : mServiceProxy->listServices()) {
        // 根据manifest.xml,这里的instance:legacy/0
        this->addProviderLocked(instance);
    }

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

    return OK;
}
status_t CameraProviderManager::addProviderLocked(const std::string& newProvider) {
    // 判断newProviders是否已经注册(第一次启动,这里是没有注册的)
    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;
        }
    }

    sp<provider::V2_4::ICameraProvider> interface;
    // 获取底层CameraProvider接口
    // newProvider: legacy/0
    interface = mServiceProxy->tryGetService(newProvider);

    if (interface == nullptr) {
        ALOGE("%s: Camera provider HAL '%s' is not actually available", __FUNCTION__,
                newProvider.c_str());
        return BAD_VALUE;
    }
	// 通过ProviderInfo来保存管理Provider信息
    sp<ProviderInfo> providerInfo = new ProviderInfo(newProvider, this);
    status_t res = providerInfo->initialize(interface, mDeviceState);
    if (res != OK) {
        return res;
    }

    mProviders.push_back(providerInfo);

    return OK;
}

这里再看下tryGetService这个函数,先看这个函数的头文件声明

/android/out/soong/.intermediates/hardware/interfaces/camera/provider/2.4/android.hardware.camera.provider@2.4_genc++_headers/gen/android/hardware/camera/provider/2.4/ICameraProvider.h

static ::android::sp<ICameraProvider> tryGetService(const std::string &serviceName="default", bool getStub=false);

/android/out/soong/.intermediates/hardware/interfaces/camera/provider/2.5/android.hardware.camera.provider@2.5_genc++/gen/android/hardware/camera/provider/2.5/CameraProviderAll.cpp

::android::sp<ICameraProvider> ICameraProvider::tryGetService(const std::string &serviceName, const bool getStub) {
    return ::android::hardware::details::getServiceInternal<BpHwCameraProvider>(serviceName, false, getStub);
}

/android/system/libhidl/transport/include/hidl/HidlTransportSupport.h

sp<IType> getServiceInternal(const std::string& instance, bool retry, bool getStub) {
    using ::android::hidl::base::V1_0::IBase;
	
    // 这里返回的是BpHwBase
    sp<IBase> base = getRawServiceInternal(IType::descriptor, instance, retry, getStub);

    if (base == nullptr) {
        return nullptr;
    }
	// 因此这里的值就是true
    if (base->isRemote()) {
        // getRawServiceInternal guarantees we get the proper class
        return sp<IType>(new BpType(getOrCreateCachedBinder(base.get())));
    }

    return IType::castFrom(base);
}

这里继续看getRawServiceInternal这个函数

/android/system/libhidl/transport/ServiceManagement.cpp

sp<::android::hidl::base::V1_0::IBase> getRawServiceInternal(const std::string& descriptor,
                                                             const std::string& instance,
                                                             bool retry, bool getStub) {
    using Transport = IServiceManager1_0::Transport;
    sp<Waiter> waiter;

    sp<IServiceManager1_1> sm;
    Transport transport = Transport::EMPTY;
    if (kIsRecovery) {
        transport = Transport::PASSTHROUGH;
    } else {
        // 拿到HwSericeManager的对象
        sm = defaultServiceManager1_1();
        if (sm == nullptr) {
            ALOGE("getService: defaultServiceManager() is null");
            return nullptr;
        }
		// 获取CameraProvider服务的transport,确认是直通式:PassThrough,还是绑定式:HwBinder
        // 可以在/vendor/etc/vintf/manifest.xml在中查看这个标签的值(hwbinder
        Return<Transport> transportRet = sm->getTransport(descriptor, instance);

        if (!transportRet.isOk()) {
            ALOGE("getService: defaultServiceManager()->getTransport returns %s",
                  transportRet.description().c_str());
            return nullptr;
        }
        transport = transportRet;
    }

    const bool vintfHwbinder = (transport == Transport::HWBINDER); // 绑定式服务
    const bool vintfPassthru = (transport == Transport::PASSTHROUGH); // 直通式服务
    const bool trebleTestingOverride = isTrebleTestingOverride();
    const bool allowLegacy = !kEnforceVintfManifest || (trebleTestingOverride && kDebuggable);
    const bool vintfLegacy = (transport == Transport::EMPTY) && allowLegacy;

    if (!kEnforceVintfManifest) {
        ALOGE("getService: Potential race detected. The VINTF manifest is not being enforced. If "
              "a HAL server has a delay in starting and it is not in the manifest, it will not be "
              "retrieved. Please make sure all HALs on this device are in the VINTF manifest and "
              "enable PRODUCT_ENFORCE_VINTF_MANIFEST on this device (this is also enabled by "
              "PRODUCT_FULL_TREBLE). PRODUCT_ENFORCE_VINTF_MANIFEST will ensure that no race "
              "condition is possible here.");
        sleep(1);
    }
	// 这里的getStub的值是false
    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()
        }
        // 如果是绑定式的服务,调用BpHwServiceManager::get()
        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;
        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();
    }

    if (getStub || vintfPassthru || vintfLegacy) {
        // 如果是直通式的服务,获取直通式的HwServiceManager对象来获取服务
        const sp<IServiceManager1_0> pm = getPassthroughServiceManager();
        if (pm != nullptr) {
            sp<IBase> base = pm->get(descriptor, instance).withDefault(nullptr);
            if (!getStub || trebleTestingOverride) {
                base = wrapPassthrough(base);
            }
            return base;
        }
    }

    return nullptr;
}

本平台采用的是绑定式的服务,继续在看get方法:

out/soong/.intermediates/system/libhidl/transport/manager/1.2/android.hidl.manager@1.2_genc++_headers/gen/android/hidl/manager/1.2/BpHwServiceManager.h

::android::hardware::Return<::android::sp<::android::hidl::base::V1_0::IBase>> get(const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name) override;

out/soong/.intermediates/system/libhidl/transport/manager/1.2/android.hidl.manager@1.2_genc++/gen/android/hidl/manager/1.2/ServiceManagerAll.cpp

// Methods from ::android::hidl::manager::V1_0::IServiceManager follow.
::android::hardware::Return<::android::sp<::android::hidl::base::V1_0::IBase>> BpHwServiceManager::get(const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name){
    ::android::hardware::Return<::android::sp<::android::hidl::base::V1_0::IBase>>  _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_get(this, this, fqName, name);

    return _hidl_out;
}

out/soong/.intermediates/system/libhidl/transport/manager/1.0/android.hidl.manager@1.0_genc++/gen/android/hidl/manager/1.0/ServiceManagerAll.cpp

// Methods from ::android::hidl::manager::V1_0::IServiceManager follow.
::android::hardware::Return<::android::sp<::android::hidl::base::V1_0::IBase>> BpHwServiceManager::_hidl_get(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name) {
    #ifdef __ANDROID_DEBUGGABLE__
    bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
    const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
    #else
    (void) _hidl_this_instrumentor;
    #endif // __ANDROID_DEBUGGABLE__
    ::android::ScopedTrace PASTE(___tracer, __LINE__) (ATRACE_TAG_HAL, "HIDL::IServiceManager::get::client");
    #ifdef __ANDROID_DEBUGGABLE__
    if (UNLIKELY(mEnableInstrumentation)) {
        std::vector<void *> _hidl_args;
        _hidl_args.push_back((void *)&fqName);
        _hidl_args.push_back((void *)&name);
        for (const auto &callback: mInstrumentationCallbacks) {
            callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "get", &_hidl_args);
        }
    }
    #endif // __ANDROID_DEBUGGABLE__

    ::android::hardware::Parcel _hidl_data;
    ::android::hardware::Parcel _hidl_reply;
    ::android::status_t _hidl_err;
    ::android::status_t _hidl_transact_err;
    ::android::hardware::Status _hidl_status;

    ::android::sp<::android::hidl::base::V1_0::IBase> _hidl_out_service;

    _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
    if (_hidl_err != ::android::OK) { goto _hidl_error; }

    size_t _hidl_fqName_parent;

    _hidl_err = _hidl_data.writeBuffer(&fqName, sizeof(fqName), &_hidl_fqName_parent);
    if (_hidl_err != ::android::OK) { goto _hidl_error; }

    _hidl_err = ::android::hardware::writeEmbeddedToParcel(
            fqName,
            &_hidl_data,
            _hidl_fqName_parent,
            0 /* parentOffset */);

    if (_hidl_err != ::android::OK) { goto _hidl_error; }

    size_t _hidl_name_parent;

    _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
    if (_hidl_err != ::android::OK) { goto _hidl_error; }

    _hidl_err = ::android::hardware::writeEmbeddedToParcel(
            name,
            &_hidl_data,
            _hidl_name_parent,
            0 /* parentOffset */);

    if (_hidl_err != ::android::OK) { goto _hidl_error; }

    _hidl_transact_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(1 /* get */, _hidl_data, &_hidl_reply, 0);
    if (_hidl_transact_err != ::android::OK) 
    {
        _hidl_err = _hidl_transact_err;
        goto _hidl_error;
    }

    _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
    if (_hidl_err != ::android::OK) { goto _hidl_error; }

    if (!_hidl_status.isOk()) { return _hidl_status; }

    {
        ::android::sp<::android::hardware::IBinder> _hidl_binder;
        _hidl_err = _hidl_reply.readNullableStrongBinder(&_hidl_binder);
        if (_hidl_err != ::android::OK) { goto _hidl_error; }

        _hidl_out_service = ::android::hardware::fromBinder<::android::hidl::base::V1_0::IBase,::android::hidl::base::V1_0::BpHwBase,::android::hidl::base::V1_0::BnHwBase>(_hidl_binder);
    }

    #ifdef __ANDROID_DEBUGGABLE__
    if (UNLIKELY(mEnableInstrumentation)) {
        std::vector<void *> _hidl_args;
        _hidl_args.push_back((void *)&_hidl_out_service);
        for (const auto &callback: mInstrumentationCallbacks) {
            callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "get", &_hidl_args);
        }
    }
    #endif // __ANDROID_DEBUGGABLE__

    return ::android::hardware::Return<::android::sp<::android::hidl::base::V1_0::IBase>>(_hidl_out_service);

_hidl_error:
    _hidl_status.setFromStatusT(_hidl_err);
    return ::android::hardware::Return<::android::sp<::android::hidl::base::V1_0::IBase>>(_hidl_status);
}

这个函数还没开特别明白,后边有时间在看。总之这里最后反会的是BpHwBase对象。

3.3 providerInfo->initialize(interface, mDeviceState)分析

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

status_t CameraProviderManager::ProviderInfo::initialize(
        sp<provider::V2_4::ICameraProvider>& interface,
        hardware::hidl_bitfield<provider::V2_5::DeviceState> currentDeviceState) {
    ......

    // Get initial list of camera devices, if any
    // 通过CameraProvider获取摄像头设备信息
    std::vector<std::string> devices;
    hardware::Return<void> ret = interface->getCameraIdList([&status, this, &devices](
            Status idStatus,
            const hardware::hidl_vec<hardware::hidl_string>& cameraDeviceNames) {
        status = idStatus;
        if (status == Status::OK) {
            for (auto& name : cameraDeviceNames) {
                uint16_t major, minor;
                std::string type, id;
                status_t res = parseDeviceName(name, &major, &minor, &type, &id);
                if (res != OK) {
                    ALOGE("%s: Error parsing deviceName: %s: %d", __FUNCTION__, name.c_str(), res);
                    status = Status::INTERNAL_ERROR;
                } else {
                    devices.push_back(name);
                    mProviderPublicCameraIds.push_back(id);
                }
            }
        } });
    ......
    for (auto& device : devices) {
        std::string id;
        // 根据获取到的摄像头设备信息,调用addDevice
        status_t res = addDevice(device, 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;
        }
    }
	......
    return OK;
}

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;

    status_t res = parseDeviceName(name, &major, &minor, &type, &id);
    ......

    std::unique_ptr<DeviceInfo> deviceInfo;
    switch (major) {
        ......
        case 3:
            // 创建DeviceInfo对象
            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;
    bool isAPI1Compatible = deviceInfo->isAPI1Compatible();
	// 缓存DeviceInfo对象
    mDevices.push_back(std::move(deviceInfo));
	......
    return OK;
}

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) {
    Status status;
	// 传入的模板类是DeviceInfoe3
    // 获取到hal层CameraDevice的接口
    auto cameraInterface =
            startDeviceInterface<typename DeviceInfoT::InterfaceT>(name);
    if (cameraInterface == nullptr) return nullptr;

    CameraResourceCost resourceCost;
    // 获取camera冲突/负载相关信息
    cameraInterface->getResourceCost([&status, &resourceCost](
        Status s, CameraResourceCost cost) {
                status = s;
                resourceCost = cost;
            });
    ......
    return std::unique_ptr<DeviceInfo>(
        new DeviceInfoT(name, tagId, id, minorVersion, resourceCost, this,
                mProviderPublicCameraIds, cameraInterface));
}

template<>
sp<device::V3_2::ICameraDevice>
CameraProviderManager::ProviderInfo::startDeviceInterface
        <device::V3_2::ICameraDevice>(const std::string &name) {
    Status status;
    sp<device::V3_2::ICameraDevice> cameraInterface;
    hardware::Return<void> ret;
    const sp<provider::V2_4::ICameraProvider> interface = startProviderInterface();
    if (interface == nullptr) {
        return nullptr;
    }
    // 这里的HAL实现是CameraDevice
    ret = interface->getCameraDeviceInterface_V3_x(name, [&status, &cameraInterface](
        Status s, sp<device::V3_2::ICameraDevice> interface) {
                status = s;
                cameraInterface = interface;
            });
    ......
    return cameraInterface;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/992124.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存