欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Camera Open 流程源码分析

程序员文章站 2022-03-31 08:01:12
和你一起终身学习,这里是程序员Android经典好文推荐,通过阅读本文,您将收获以下知识点:1.app层 MainActivity.java CameraManager 可以直接调用 其......

Camera Open 流程源码分析

和你一起终身学习,这里是程序员Android

经典好文推荐,通过阅读本文,您将收获以下知识点:

1.app层 MainActivity.java CameraManager 可以直接调用 其openCamera 方法

getCameraIdList 用来存储可用Camera设备 list, openCamera 成功后会调用CameraDevice.StateCallback#onOpened,

然后会创建Session CameraDevice#createCaptureSession 以及拍照CameraDevice#createCaptureRequest等等。

public class MainActivity extends AppCompatActivity {

    protected void onCreate(@Nullable Bundle savedInstanceState) {

    ... ...
    //
    CameraManager mCameraManager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
    ... ...
    
    }
  

2.CameraManager.java
(frameworks\base\core\java\android\hardware\camera2)

CameraManager 会根据传递过来的参数不同,调用不同的Opencamera 方法。


    @RequiresPermission(android.Manifest.permission.CAMERA)
    public void openCamera(@NonNull String cameraId,
            @NonNull final CameraDevice.StateCallback callback, @Nullable Handler handler)
            throws CameraAccessException {

        openCameraForUid(cameraId, callback, CameraDeviceImpl.checkAndWrapHandler(handler),
                USE_CALLING_UID);
    }
    // CameraDeviceImpl.checkAndWrapHandler 会将 Handler 封装成Executor 类型 
    public static Executor checkAndWrapHandler(Handler handler) {
        return new CameraHandlerExecutor(checkHandler(handler));
    }
    
    @RequiresPermission(android.Manifest.permission.CAMERA)
    public void openCamera(@NonNull String cameraId,
            @NonNull @CallbackExecutor Executor executor,
            @NonNull final CameraDevice.StateCallback callback)
            throws CameraAccessException {
        
        openCameraForUid(cameraId, callback, executor, USE_CALLING_UID);
    }
    

从代码中看,openCamera 参数主要区别是 CallbackExecutor 、Handler 这两个,最终都会走到 openCameraForUid 方法。
openCameraForUid 主要是 根据 Camera id 打开一个Camera 连接。

    public void openCameraForUid(@NonNull String cameraId,
            @NonNull final CameraDevice.StateCallback callback, @NonNull Executor executor,
            int clientUid)
            throws CameraAccessException {
            // 
            openCameraDeviceUserAsync(cameraId, callback, executor, clientUid);
            
    }


openCameraForUid 会调用 openCameraDeviceUserAsync 方法去帮助opencamera 连接的创建

    private CameraDevice openCameraDeviceUserAsync(String cameraId,
            CameraDevice.StateCallback callback, Executor executor, final int uid)
            throws CameraAccessException {
            // 获取 特定camera的特性
            CameraCharacteristics characteristics = getCameraCharacteristics(cameraId);
            
            android.hardware.camera2.impl.CameraDeviceImpl deviceImpl = new  CameraDeviceImpl();
            ICameraDeviceCallbacks callbacks = deviceImpl.getCallbacks()
            
              if (supportsCamera2ApiLocked(cameraId)) {
                    // Use cameraservice's cameradeviceclient implementation for HAL3.2+ devices
                    ICameraService cameraService = CameraManagerGlobal.get().getCameraService();
                    
                    cameraService.connectDevice(callbacks, cameraId,mContext.getOpPackageName(), uid);
                    
              }else{
                    ... ...
              }
            // TODO: factor out callback to be non-nested, then move setter to constructor
            // For now, calling setRemoteDevice will fire initial
            // onOpened/onUnconfigured callbacks.
            // This function call may post onDisconnected and throw CAMERA_DISCONNECTED if
            // cameraUser dies during setup.
            deviceImpl.setRemoteDevice(cameraUser);
            
    }

cameraService是通过Binder 继承 ICameraServiceListener.Stub

    private static final class CameraManagerGlobal extends ICameraServiceListener.Stub
            implements IBinder.DeathRecipient {
                // This must match the ICameraService definition
                private static final String CAMERA_SERVICE_BINDER_NAME = "media.camera";
                
                public ICameraService getCameraService() {
                    
                    synchronized(mLock) {
                        // 
                        connectCameraServiceLocked();
                        return mCameraService;
                    }
                }
                
                private void connectCameraServiceLocked() {
                     IBinder cameraServiceBinder = ServiceManager.getService(CAMERA_SERVICE_BINDER_NAME);
                
                     ICameraService cameraService = ICameraService.Stub.asInterface(cameraServiceBinder);
                     
                     for (CameraStatus c : cameraStatuses) {
                        onStatusChangedLocked(c.status, c.cameraId);
                     }
                     mCameraService = cameraService;
                }       
            }

3.CameraService.cpp
(frameworks\av\services\camera\libcameraservice)

cameraService.connectDevice 通过AIDL 到用到 CameraService.cpp 中的connectDevice 方法。

Status CameraService::connectDevice(
        const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
        const String16& cameraId,
        const String16& clientPackageName,
        int clientUid,
        /*out*/
        sp<hardware::camera2::ICameraDeviceUser>* device) {
            //调用connectHelper 方法
            ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
            /*api1CameraId*/-1,
            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageNameAdj,
            clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, /*out*/client);
        
        }

connectDevice 会调用到 connectHelper 方法


Status CameraService::connectHelper(){

        // 闪光灯进入预准备阶段
        mFlashlight->prepareDeviceOpen(cameraId);

        //获取当前设备的Version
        int deviceVersion = getDeviceVersion(cameraId, /*out*/&facing);
        
        
        // 初始化CameraproviderManager
        err = client->initialize(mCameraProviderManager, mMonitorTags);
        
        }

4.CameraProviderManager.cpp
(frameworks\av\services\camera\libcameraservice\common)


status_t CameraProviderManager::initialize(wp<CameraProviderManager::StatusListener> listener,
        ServiceInteractionProxy* proxy) {
        // 调用 addProviderLocked 方法
        for (const auto& instance : mServiceProxy->listServices()) {
            this->addProviderLocked(instance);
        }
        
        }
        
status_t CameraProviderManager::addProviderLocked(const std::string& newProvider) {
         
        sp<ProviderInfo> providerInfo = new ProviderInfo(newProvider, this);
        status_t res = providerInfo->initialize(interface, mDeviceState);

}

//ProviderInfo::initialize 初始化方法
status_t CameraProviderManager::ProviderInfo::initialize(){


     status_t res = addDevice(device, common::V1_0::CameraDeviceStatus::PRESENT, &id);

}       


status_t CameraProviderManager::ProviderInfo::addDevice(const std::string& name,
        CameraDeviceStatus initialStatus, /*out*/ std::string* parsedId) {
        
        //
        deviceInfo = initializeDeviceInfo<DeviceInfo3>(name, mProviderTagid,
                    id, minor);
        
        }
        
        
std::unique_ptr<CameraProviderManager::ProviderInfo::DeviceInfo>
    CameraProviderManager::ProviderInfo::initializeDeviceInfo(){
        // 后续调用待完善 如何 跳转到 Camera3device.cpp 的initialize 方法
        return std::unique_ptr<DeviceInfo>(
        new DeviceInfoT(name, tagId, id, minorVersion, resourceCost, this,
                mProviderPublicCameraIds, cameraInterface));
    }
    
 

5.Camera3Device.cpp
(frameworks\av\services\camera\libcameraservice\device3)

status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {

        // 调用 CameraProviderManager openSession
        ATRACE_BEGIN("CameraHal::openSession");
        status_t res = manager->openSession(mId.string(), this,
                /*out*/ &session);
        ATRACE_END();

        return initializeCommonLocked();
}

6.CameraProviderManager.cpp
(frameworks\av\services\camera\libcameraservice\common)

status_t CameraProviderManager::openSession(const std::string &id,
        const sp<device::V3_2::ICameraDeviceCallback>& callback,
        /*out*/
        sp<device::V3_2::ICameraDeviceSession> *session) {
        
            auto interface = deviceInfo3->startDeviceInterface<
            CameraProviderManager::ProviderInfo::DeviceInfo3::InterfaceT>();
            
            ret = interface->open(callback, [&status, &session]
            (Status s, const sp<device::V3_2::ICameraDeviceSession>& cameraSession) {
                status = s;
                if (status == Status::OK) {
                    *session = cameraSession;
                }
            });
        
        
        }

7.ICameraDevice.hal
(hardware\interfaces\camera\device\3.2)

//Power on and initialize this camera device for active use, returning a
//session handle for active operations.
 open(ICameraDeviceCallback callback) generates
            (Status status, ICameraDeviceSession session);
            

8.CameraDevice.cpp
(hardware\interfaces\camera\device\3.2\default)

Return<void> CameraDevice::open(const sp<ICameraDeviceCallback>& callback,
        ICameraDevice::open_cb _hidl_cb)  {
        
        
        /** Open HAL device */
        status_t res;
        camera3_device_t *device;
        // 1. 开始 open Hal Device 
        ATRACE_BEGIN("camera3->open");
        res = mModule->open(mCameraId.c_str(),
                reinterpret_cast<hw_device_t**>(&device));
        ATRACE_END();
        
        // 2. 获取Camera 信息
        res = mModule->getCameraInfo(mCameraIdInt, &info);
        
        // 3. 创建 CameraDeviceSession
        session = createSession(device, info.static_camera_characteristics, callback);
        }
  1. CameraModule.cpp
    (hardware\interfaces\camera\common\1.0\default)

int CameraModule::open(const char* id, struct hw_device_t** device) {
    int res;
    ATRACE_BEGIN("camera_module->open");
    res = filterOpenErrorCode(mModule->common.methods->open(&mModule->common, id, device));
    ATRACE_END();
    return res;
}

10.Camxhal3entry.cpp
(vendor\qcom\proprietary\camx\src\core\hal)

int open(
    const struct hw_module_t*   pHwModuleAPI,
    const char*                 pCameraIdAPI,
    struct hw_device_t**        ppHwDeviceAPI)
{
    /// @todo (CAMX-43) - Reload Jumptable from settings
    JumpTableHAL3* pHAL3 = static_cast<JumpTableHAL3*>(g_dispatchHAL3.GetJumpTable());
    
    return pHAL3->open(pHwModuleAPI, pCameraIdAPI, ppHwDeviceAPI);
}

11.Camxhal3.cpp
(vendor\qcom\proprietary\camx\src\core\hal)

static int open(){
    // 检查CameraId 是否有效
    cameraId = OsUtils::StrToUL(pCameraIdAPI, &pNameEnd, 10);
    
    // 检查闪光灯状态,如果 on 状态,需要off 
    HAL3Module::GetInstance()->ReserveTorchForCamera(
                GetCHIAppCallbacks()->chi_remap_camera_id(cameraId, IdRemapTorch), cameraId);
    
    // 调用 Camxhal3module ProcessCameraOpen 方法
    result = HAL3Module::GetInstance()->ProcessCameraOpen(logicalCameraId, &extend);
    
    // 创建HalDevice 实例并初始化
    pHALDevice = HALDevice::Create(pHwModule, logicalCameraId, cameraId);
}

12.Camxhal3module.cpp
(vendor\qcom\proprietary\camx\src\core\hal)

CamxResult HAL3Module::ProcessCameraOpen(){

    result = m_ChiAppCallbacks.chi_extend_open(logicalCameraId, pPriv);
}

13.Chxextensioninterface.cpp
(vendor\qcom\proprietary\chi-cdk\core\chiframework)

static CDKResult chi_extend_open(){

    ExtensionModule* pExtensionModule = ExtensionModule::GetInstance();
    CHX_LOG_DEBUG("[OP_EXT] OPEN_CAMERA E cameraId %d", cameraId);
    CDKResult result = pExtensionModule->ExtendOpen(cameraId, priv);
    CHX_LOG_DEBUG("[OP_EXT] OPEN_CAMERA X");
}

14.Chxextensionmodule.cpp
(vendor\qcom\proprietary\chi-cdk\core\chiframework)

CDKResult ExtensionModule::ExtendOpen(){

    // 调用 Perflock 提高 opencamera  性能
    m_pPerfLockManager[logicalCameraId] = PerfLockManager::Create();
    
    if (PERF_LOCK_OPEN_CAMERA != m_previousPowerHint)
    { 

         m_pPerfLockManager[logicalCameraId]->ReleasePerfLock(m_previousPowerHint);
         m_pPerfLockManager[logicalCameraId]->AcquirePerfLock(PERF_LOCK_OPEN_CAMERA, 10000);
         m_previousPowerHint = PERF_LOCK_OPEN_CAMERA;
    }
    // open 结束返回到 camxhal3.cpp
}

15.Camxhal3.cpp
(vendor\qcom\proprietary\camx\src\core\hal)

static int open(){
    // 检查CameraId 是否有效
    cameraId = OsUtils::StrToUL(pCameraIdAPI, &pNameEnd, 10);
    
    // 检查闪光灯状态,如果 on 状态,需要off 
    HAL3Module::GetInstance()->ReserveTorchForCamera(
                GetCHIAppCallbacks()->chi_remap_camera_id(cameraId, IdRemapTorch), cameraId);
    
    // 调用 Camxhal3module ProcessCameraOpen 方法
    result = HAL3Module::GetInstance()->ProcessCameraOpen(logicalCameraId, &extend);
    
    // 创建HalDevice 实例并初始化
    pHALDevice = HALDevice::Create(pHwModule, logicalCameraId, cameraId);
}

16.Camxhaldevice.cpp
(vendor\qcom\proprietary\camx\src\core\hal)


HALDevice* HALDevice::Create(){

    result = pHALDevice->Initialize(pHwModule, cameraId);

}

CamxResult HALDevice::Initialize(){
  ... ...
  
  // 初始化完成后,需要返回 CameraDevice.cpp 中继续执行 open 中的方法
}

17.CameraDevice.cpp
(hardware\interfaces\camera\device\3.2\default)

Return<void> CameraDevice::open(const sp<ICameraDeviceCallback>& callback,
        ICameraDevice::open_cb _hidl_cb)  {
        
        
        /** Open HAL device */
        status_t res;
        camera3_device_t *device;
        // 1. 开始 open Hal Device 
        ATRACE_BEGIN("camera3->open");
        res = mModule->open(mCameraId.c_str(),
                reinterpret_cast<hw_device_t**>(&device));
        ATRACE_END();
        
        // 2. 获取Camera 信息
        res = mModule->getCameraInfo(mCameraIdInt, &info);
        
        // 3. 创建 CameraDeviceSession
        session = createSession(device, info.static_camera_characteristics, callback);
        }
        
        //3. 创建 CameraDeviceSession 方法实现
        sp<CameraDeviceSession> CameraDevice::createSession(camera3_device_t* device,
            const camera_metadata_t* deviceInfo,
            const sp<ICameraDeviceCallback>& callback) {
            return new CameraDeviceSession(device, deviceInfo, callback);
        }
        

18.CameraDeviceSession.cpp
(hardware\interfaces\camera\device\3.2\default) 62313 2020/8/11

CameraDeviceSession::CameraDeviceSession(){

    //调用 initialize 方法
    mInitFail = initialize();
    
}

bool CameraDeviceSession::initialize() {

    // 初始化完成之后返回 CameraProviderManager
}

Camera Open 流程源码分析

CamxOpen流程(参考网络)

至此,本篇已结束。转载网络的文章,小编觉得很优秀,欢迎点击阅读原文,支持原创作者,如有侵权,恳请联系小编删除。同时感谢您的阅读,期待您的关注。

Camera Open 流程源码分析

点个在看,方便您使用时快速查找!

本文地址:https://blog.csdn.net/wjky2014/article/details/110212051