android6.0源码分析之Camera API2.0下的初始化流程分析

在文章android源码分析之Camera API2.0简介中,对Camera API2.0的框架以及代码做了简单介绍,本文将基于android6.0源码,分析Camera API2.0下的Camera2内置应用中,对Camera的初始化的流程分析,主要涉及Camera HAL3.0,Java 层的IPC Binder,Native层的CameraService的C/S服务架构等关键点。
Camera2相关分析文章目录:
android6.0源码分析之Camera API2.0简介
android6.0源码分析之Camera2 HAL分析
android6.0源码分析之Camera API2.0下的初始化流程分析
android6.0源码分析之Camera API2.0下的Preview(预览)流程分析
android6.0源码分析之Camera API2.0下的Capture流程分析

1、Camera2初始化的应用层流程分析

Camera2的初始化流程与Camera1.0有所区别,本文将就Camera2的内置应用来分析Camera2.0的初始化过程。Camera2.0首先启动的是CameraActivity,而它继承自QuickActivity,在代码中你会发现没有重写OnCreate等生命周期方法,因为此处采用的是模板方法的设计模式,在QuickActivity中的onCreate方法调用的是onCreateTasks等方法,所以要看onCreate方法就只须看onCreateTasks方法即可:

//CameraActivity.java
@Override
public void onCreateTasks(Bundle state) {
    Profile profile = mProfiler.create("CameraActivity.onCreateTasks")
                            .start();
    ...
    mOnCreateTime = System.currentTimeMillis();
    mAppContext = getApplicationContext();
    mMainHandler = new MainHandler(this, getMainLooper());
    …
    try {
        //初始化OneCameraOpener对象
        ①mOneCameraOpener = OneCameraModule.provideOneCameraOpener(
                mFeatureConfig, mAppContext,mActiveCameraDeviceTracker,
                ResolutionUtil.getDisplayMetrics(this));
        mOneCameraManager = OneCameraModule.provideOneCameraManager();
    } catch (OneCameraException e) {...}
    …
    //建立模块信息
    ②ModulesInfo.setupModules(mAppContext, mModuleManager, mFeatureConfig);
    …
    //进行初始化
    ③mCurrentModule.init(this, isSecureCamera(), isCaptureIntent());
    …
}

如代码所示,重要的有以上三点,先看第一点:

//OneCameraModule.java
public static OneCameraOpener provideOneCameraOpener(OneCameraFeatureConfig     
            featureConfig, Context context, ActiveCameraDeviceTracker 
            activeCameraDeviceTracker,DisplayMetrics displayMetrics) 
            throws OneCameraException {
    //创建OneCameraOpener对象
    Optional<OneCameraOpener> manager = Camera2OneCameraOpenerImpl.create(
              featureConfig, context, activeCameraDeviceTracker, displayMetrics);
    if (!manager.isPresent()) {
        manager = LegacyOneCameraOpenerImpl.create();
    }
    ...
    return manager.get();
}

它调用Camera2OneCameraOpenerImpl的create方法来获得一个OneCameraOpener对象,以供CameraActivity之后的操作使用,继续看create方法:

//Camera2OneCameraOpenerImpl.java
public static Optional<OneCameraOpener> create(OneCameraFeatureConfig 
            featureConfig, Context context, ActiveCameraDeviceTracker 
            activeCameraDeviceTracker, DisplayMetrics displayMetrics) {
    ...
    CameraManager cameraManager;
    try {
        cameraManager = AndroidServices.instance().provideCameraManager();
    } catch (IllegalStateException ex) {...}
    //新建一个Camera2OneCameraOpenerImpl对象
    OneCameraOpener oneCameraOpener = new Camera2OneCameraOpenerImpl(
                featureConfig, context, cameraManager,
                activeCameraDeviceTracker, displayMetrics);
    return Optional.of(oneCameraOpener);
}

很明显,它首先获取一个cameraManger对象,然后根据这个cameraManager对象来新创建了一个Camera2OneCameraOpenerImpl对象,所以第一步主要是为了获取一个OneCameraOpener对象,它的实现为Camera2OneCameraOpenerImpl类。
继续看第二步,ModulesInfo.setupModules:

// ModulesInfo.java
public static void setupModules(Context context, ModuleManager moduleManager,
            OneCameraFeatureConfig config) {
        Resources res = context.getResources();
        int photoModuleId = context.getResources().getInteger(
            R.integer.camera_mode_photo);
        //注册Photo模块
        registerPhotoModule(moduleManager, photoModuleId, 
            SettingsScopeNamespaces.PHOTO,config.isUsingCaptureModule());
        //计算你还Photo模块设置为默认的模块
        moduleManager.setDefaultModuleIndex(photoModuleId);
        //注册Videa模块
        registerVideoModule(moduleManager, res.getInteger(
            R.integer.camera_mode_video),SettingsScopeNamespaces.VIDEO);
        if (PhotoSphereHelper.hasLightCycleCapture(context)) {//开启闪光
            //注册广角镜头
            registerWideAngleModule(moduleManager, res.getInteger(
                R.integer.camera_mode_panorama),SettingsScopeNamespaces
                .PANORAMA);
            //注册光球模块
            registerPhotoSphereModule(moduleManager,res.getInteger(
                R.integer.camera_mode_photosphere),
                SettingsScopeNamespaces.PANORAMA);
        }
        //若需重新聚焦
        if (RefocusHelper.hasRefocusCapture(context)) {
            //注册重聚焦模块
            registerRefocusModule(moduleManager, res.getInteger(
                R.integer.camera_mode_refocus),
                SettingsScopeNamespaces.REFOCUS);
        }
        //如果有色分离模块
        if (GcamHelper.hasGcamAsSeparateModule(config)) {
            //注册色分离模块
            registerGcamModule(moduleManager, res.getInteger(
                R.integer.camera_mode_gcam),SettingsScopeNamespaces.PHOTO,
                config.getHdrPlusSupportLevel(OneCamera.Facing.BACK));
        }
        int imageCaptureIntentModuleId = res.getInteger(
            R.integer.camera_mode_capture_intent);
        registerCaptureIntentModule(moduleManager, 
            imageCaptureIntentModuleId,SettingsScopeNamespaces.PHOTO,
            config.isUsingCaptureModule());
}

代码根据配置信息,进行一系列模块的注册,其中PhotoModule和VideoModule被注册,而其他的module则是根据配置来进行的,因为打开Camera应用,既可以拍照片也可以拍视频,此处,只分析PhoneModule的注册:

// ModulesInfo.java
private static void registerPhotoModule(ModuleManager moduleManager, final 
            int moduleId, final String namespace, 
            final boolean enableCaptureModule) {
        //向ModuleManager注册PhotoModule模块
        moduleManager.registerModule(new ModuleManager.ModuleAgent() {

            @Override
            public int getModuleId() {
                return moduleId;
            }

            @Override
            public boolean requestAppForCamera() {
                return !enableCaptureModule;
            }

            @Override
            public String getScopeNamespace() {
                return namespace;
            }

            @Override
            public ModuleController createModule(AppController app, Intent 
                    intent) {
                Log.v(TAG, "EnableCaptureModule = " + enableCaptureModule);
                //创建ModuleController
                return enableCaptureModule ? new CaptureModule(app) 
                        : new PhotoModule(app);
            }
        });
}

由代码可知,它最终是由ModuleManager来新建一个CaptureModule实例,而CaptureModule其实实现了ModuleController ,即创建了一个CaptureModule模式下的ModuleController对象,而真正的CaptureModule的具体实现为ModuleManagerImpl。
至此,前两步已经获得了OneCameraOpener以及新建了ModuleController,并进行了注册,接下来分析第三步,mCurrentModule.init(this, isSecureCamera(), isCaptureIntent()):

//CaptureModule.java
public void init(CameraActivity activity, boolean isSecureCamera, boolean 
            isCaptureIntent) {
        ...
        HandlerThread thread = new HandlerThread("CaptureModule.mCameraHandler");
        thread.start();
        mCameraHandler = new Handler(thread.getLooper());
        //获取第一步中创建的OneCameraOpener对象
        mOneCameraOpener = mAppController.getCameraOpener();

        try {
            //获取前面创建的OneCameraManager对象
            mOneCameraManager = OneCameraModule.provideOneCameraManager();
        } catch (OneCameraException e) {
            Log.e(TAG, "Unable to provide a OneCameraManager. ", e);
        }
       `...
        //新建CaptureModule的UI
        mUI = new CaptureModuleUI(activity, mAppController.
                getModuleLayoutRoot(), mUIListener);
        //设置预览状态的监听
        mAppController.setPreviewStatusListener(mPreviewStatusListener);
        synchronized (mSurfaceTextureLock) {
            //获取SurfaceTexture
            mPreviewSurfaceTexture = mAppController.getCameraAppUI()
                .getSurfaceTexture();
        }  
}

首先获取前面创建的OneCameraOpener对象以及OneCameraManager对象,然后再设置预览状态监听,这里主要分析预览状态的监听:

//CaptureModule.java
private final PreviewStatusListener mPreviewStatusListener = new 
    PreviewStatusListener() {
        ...

        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, 
            int width, int height) {
            updatePreviewTransform(width, height, true);
            synchronized (mSurfaceTextureLock) {
                mPreviewSurfaceTexture = surface;
            }
            //打开Camera
            reopenCamera();
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
            Log.d(TAG, "onSurfaceTextureDestroyed");
            synchronized (mSurfaceTextureLock) {
                mPreviewSurfaceTexture = null;
            }
            //关闭Camera
            closeCamera();
            return true;
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, 
            int width, int height) {
            //更新预览尺寸
            updatePreviewBufferSize();
        }
        ...
    };

由代码可知,当SurfaceTexture的状态变成可用的时候,会调用reopenCamera()方法来打开Camera,所以继续分析reopenCamera()方法:

//CaptureModule.java
private void reopenCamera() {
    if (mPaused) {
        return;
    }
    AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
        @Override
        public void run() {
            closeCamera();
            if(!mAppController.isPaused()) {
                //开启Camera并开始预览
                openCameraAndStartPreview();
            }
        }
    });
}

它采用异步任务的方法,开启一个异步线程来进行启动操作,首先关闭打开的Camera,然后如果AppController不处于暂停状态,则打开Camera并启动Preview操作,所以继续分析openCameraAndStartPreview方法:

//CaptureModule.java
private void openCameraAndStartPreview() {
    ...
    if (mOneCameraOpener == null) {
        Log.e(TAG, "no available OneCameraManager, showing error dialog");
        //释放CameraOpenCloseLock锁
        mCameraOpenCloseLock.release();
        mAppController.getFatalErrorHandler().onGenericCameraAccessFailure();
        guard.stop("No OneCameraManager");
        return;
    }
    // Derive objects necessary for camera creation.
    MainThread mainThread = MainThread.create();

    //查找需要打开的CameraId
    CameraId cameraId = mOneCameraManager.findFirstCameraFacing(
        mCameraFacing);
    ...
    //打开Camera
    mOneCameraOpener.open(cameraId, captureSetting, mCameraHandler,
        mainThread, imageRotationCalculator, mBurstController, 
        mSoundPlayer,new OpenCallback() {

            @Override
            public void onFailure() {
                //进行失败的处理
                ...
            }

            @Override
            public void onCameraClosed() {
                ...
            }

            @Override
            public void onCameraOpened(@Nonnull final OneCamera camera) {
                Log.d(TAG, "onCameraOpened: " + camera);
                mCamera = camera;

                if (mAppController.isPaused()) {
                    onFailure();
                    return;
                }
                ...
                mMainThread.execute(new Runnable() {
                    @Override
                    public void run() {
                        //通知UI,Camera状态变化
                        mAppController.getCameraAppUI().onChangeCamera();
                        //使能拍照按钮
                        mAppController.getButtonManager().enableCameraButton();
                    }
                });
                //至此,Camera打开成功,开始预览                    
                camera.startPreview(new Surface(getPreviewSurfaceTexture()), 
                    new CaptureReadyCallback() {
                        @Override
                        public void onSetupFailed() {
                            ...
                        }

                        @Override
                        public void onReadyForCapture() {
                            //释放锁
                            mCameraOpenCloseLock.release();
                            mMainThread.execute(new Runnable() {
                                @Override
                                public void run() {
                                    ...
                                    onPreviewStarted();
                                    ...
                                    onReadyStateChanged(true);
                                    //设置CaptureModule为Capture准备的状态监听
                                    mCamera.setReadyStateChangedListener(
                                        CaptureModule.this);
                                        mUI.initializeZoom(mCamera.getMaxZoom());                                 
                                        mCamera.setFocusStateListener(
                                            CaptureModule.this);
                                    }
                                });
                            }
                        });
                    } 
              }, mAppController.getFatalErrorHandler());
        guard.stop("mOneCameraOpener.open()");
    }
}

首先,它主要会调用Camera2OneCameraOpenerImpl的open方法来打开Camera,并定义了开启的回调函数,对开启结束后的结果进行处理,如失败则释放mCameraOpenCloseLock,并暂停mAppController,如果打开成功,通知UI成功,并开启Camera的Preview,并且定义了Preview的各种回调操作,这里主要分析Open过程,所以继续分析:

//Camera2OneCameraOpenerImpl.java
@Override
public void open(
    ...
    mActiveCameraDeviceTracker.onCameraOpening(cameraKey);
    //打开Camera,此处调用框架层的CameraManager类的openCamera,进入frameworks层
    mCameraManager.openCamera(cameraKey.getValue(), 
        new CameraDevice.StateCallback() {
        private boolean isFirstCallback = true;
        @Override
        ...

        @Override
        public void onOpened(CameraDevice device) {
            //第一次调用此回调
            if (isFirstCallback) {
                isFirstCallback = false;
                try {
                    CameraCharacteristics characteristics = mCameraManager
                        .getCameraCharacteristics(device.getId());
                    ...
                    //创建OneCamera对象
                    OneCamera oneCamera = OneCameraCreator.create(device,
                        characteristics, mFeatureConfig, captureSetting,
                        mDisplayMetrics, mContext, mainThread,
                        imageRotationCalculator, burstController, soundPlayer,
                        fatalErrorHandler);

                    if (oneCamera != null) {
                        //如果oneCamera不为空,则回调onCameraOpened,后面将做分析
                        openCallback.onCameraOpened(oneCamera);
                    } else {
                        ...
                        openCallback.onFailure();
                    }
                } catch (CameraAccessException e) {
                    openCallback.onFailure();
                } catch (OneCameraAccessException e) {
                    Log.d(TAG, "Could not create OneCamera", e);
                    openCallback.onFailure();
                }
            }
        }
    }, handler);
    ...
}

至此,Camera的初始化流程中应用层的分析就差不多了,下一步将会调用CameraManager的openCamera方法来进入框架层,并进行Camera的初始化,下面将应用层的初始化时序图:
android6.0源码分析之Camera API2.0下的初始化流程分析_第1张图片

2、Camera2初始化的框架层流程分析

由上面的分析可知,将由应用层进入到框架层处理,将会调用CameraManager的openCamera方法,并且定义了CameraDevice的状态回调函数,具体的回调操作此处不做分析,继续跟踪openCamera()方法:

//CameraManager.java(frameworks/base/core/java/android/hardware/camera2)
@RequiresPermission(android.Manifest.permission.CAMERA)
public void openCamera(@NonNull String cameraId,@NonNull final 
        CameraDevice.StateCallback callback, @Nullable Handler handler)
        throws CameraAccessException {
    ...
    openCameraDeviceUserAsync(cameraId, callback, handler);
}

由代码可知,此处与Camera1.0有明显不同,Camera1.0是通过一个异步的线程以及JNI来调用android_hardware_camera.java里面的native_setup方法来连接Camera,其使用的是C++的Binder来与CameraService进行通信的,而此处则不一样,它直接使用的是Java层的Binder来进行通信,先看openCameraDeviceUserAsync代码:

//CameraManager.java(frameworks/base/core/java/android/hardware/camera2)
private CameraDevice openCameraDeviceUserAsync(String cameraId,
        CameraDevice.StateCallback callback, Handler handler)
        throws CameraAccessException {
    CameraCharacteristics characteristics = getCameraCharacteristics(
        cameraId);
    CameraDevice device = null;
    try {
        synchronized (mLock) {
            ICameraDeviceUser cameraUser = null;
            //初始化一个CameraDevice对象
            android.hardware.camera2.impl.CameraDeviceImpl deviceImpl =
                new android.hardware.camera2.impl.CameraDeviceImpl(cameraId,
                callback, handler, characteristics);
            BinderHolder holder = new BinderHolder();
            //获取回调
            ICameraDeviceCallbacks callbacks = deviceImpl.getCallbacks();
            int id = Integer.parseInt(cameraId);
            try {
                if (supportsCamera2ApiLocked(cameraId)) {
                    //通过Java层的Binder获取CameraService                        
                    ICameraService cameraService = CameraManagerGlobal.get()
                        .getCameraService();
                    ...
                    //通过CameraService连接Camera设备
                    cameraService.connectDevice(callbacks, id, mContext
                        .getOpPackageName(), USE_CALLING_UID, holder);
                    //获取连接成功的CameraUser对象,它用来与CameraService通信
                    cameraUser = ICameraDeviceUser.Stub.asInterface(
                        holder.getBinder());
                } else {
                    //使用遗留的API
                    cameraUser = CameraDeviceUserShim.connectBinderShim(
                        callbacks, id);
                }
            } catch (CameraRuntimeException e) {
                ...
        } catch (RemoteException e) {
            ...
            //将其包装成DeviceImpl对象,供应用层使用
            deviceImpl.setRemoteDevice(cameraUser);
            device = deviceImpl;
        }
    } catch (NumberFormatException e) {
        ...
    } catch (CameraRuntimeException e) {
        throw e.asChecked();
    }
    return device;
}

此方法的目的是通过CameraService来连接并获取CameraDevice对象,该对象用来与Camera进行通信操作。代码首先通过Java层的Binder机制获取CameraService,然后调用其connectDevice方法来连接CaneraDevice,最后Camera返回的是CameraDeviceUser对象,而接着将其封装成Jav层CameraDevice对象,而之后所有与Camera的通信都通过CameraDevice的接口来进行。接下来分析一下Native层下的CameraDevice的初始化过程:

//CameraService.cpp,其中device为输出对象
status_t CameraService::connectDevice(const sp<ICameraDeviceCallbacks>& cameraCb,int cameraId,
        const String16& clientPackageName,int clientUid,/*out*/sp<ICameraDeviceUser>& device) {

    status_t ret = NO_ERROR;
    String8 id = String8::format("%d", cameraId);
    sp<CameraDeviceClient> client = nullptr;
    ret = connectHelper<ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb, id,
            CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, API_2, false, false,
            /*out*/client);//client为输出对象
    ...
    device = client;
    return NO_ERROR;
}

Native层的connectDevice方法就是调用了connectHelper方法,所以继续分析connectHelper:

//CameraService.h
template<class CALLBACK, class CLIENT>
status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
        int halVersion, const String16& clientPackageName, int clientUid,
        apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
        /*out*/sp<CLIENT>& device) {
    status_t ret = NO_ERROR;
    String8 clientName8(clientPackageName);
    int clientPid = getCallingPid();
    ...
    sp<CLIENT> client = nullptr;
    {
        ...

        //如果有必要,给FlashLight关闭设备的机会
        mFlashlight->prepareDeviceOpen(cameraId);
        //获取CameraId
        int id = cameraIdToInt(cameraId);
        ...
        //获取Device的版本,此处为Device3
        int deviceVersion = getDeviceVersion(id, /*out*/&facing);
        sp<BasicClient> tmp = nullptr;
        //获取client对象
        if((ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
                clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
                /*out*/&tmp)) != NO_ERROR) {
            return ret;
        }
        client = static_cast<CLIENT*>(tmp.get());
        //调用client的初始化函数来初始化模块
        if ((ret = client->initialize(mModule)) != OK) {
            ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
            return ret;
        }

        sp<IBinder> remoteCallback = client->getRemote();
        if (remoteCallback != nullptr) {
            remoteCallback->linkToDeath(this);
        }
    } // lock is destroyed, allow further connect calls
    //将client赋值给输出Device
    device = client;
    return NO_ERROR;
}

CameraService根据Camera的相关参数来获取一个client,如makeClient方法,然后再调用client的initialize来进行初始化,首先看makeClient:

//CameraService.cpp
status_t CameraService::makeClient(const sp<CameraService>& cameraService,
        const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
        int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
        int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
        /*out*/sp<BasicClient>* client) {

    //将字符串的CameraId转换成整形
    int id = cameraIdToInt(cameraId);
    ...
    if (halVersion < 0 || halVersion == deviceVersion) {//判断Camera HAL版本是否和Device的版本相同
        switch(deviceVersion) {
          case CAMERA_DEVICE_API_VERSION_1_0:
            if (effectiveApiLevel == API_1) {  // Camera1 API route
                sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
                *client = new CameraClient(cameraService, tmp, packageName, id, facing,
                        clientPid, clientUid, getpid(), legacyMode);
            } else { // Camera2 API route
                ALOGW("Camera using old HAL version: %d", deviceVersion);
                return -EOPNOTSUPP;
            }
            break;
          case CAMERA_DEVICE_API_VERSION_2_0:
          case CAMERA_DEVICE_API_VERSION_2_1:
          case CAMERA_DEVICE_API_VERSION_3_0:
          case CAMERA_DEVICE_API_VERSION_3_1:
          case CAMERA_DEVICE_API_VERSION_3_2:
          case CAMERA_DEVICE_API_VERSION_3_3:
            if (effectiveApiLevel == API_1) { // Camera1 API route
                sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
                *client = new Camera2Client(cameraService, tmp, packageName, id, facing,
                        clientPid, clientUid, servicePid, legacyMode);
            } else { // Camera2 API route
                sp<ICameraDeviceCallbacks> tmp =
                        static_cast<ICameraDeviceCallbacks*>(cameraCb.get());
                *client = new CameraDeviceClient(cameraService, tmp, packageName, id,
                        facing, clientPid, clientUid, servicePid);
            }
            break;
          default:
            // Should not be reachable
            ALOGE("Unknown camera device HAL version: %d", deviceVersion);
            return INVALID_OPERATION;
        }
    } else {
        // A particular HAL version is requested by caller. Create CameraClient
        // based on the requested HAL version.
        if (deviceVersion > CAMERA_DEVICE_API_VERSION_1_0 &&
            halVersion == CAMERA_DEVICE_API_VERSION_1_0) {
            // Only support higher HAL version device opened as HAL1.0 device.
            sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
            *client = new CameraClient(cameraService, tmp, packageName, id, facing,
                    clientPid, clientUid, servicePid, legacyMode);
        } else {
            // Other combinations (e.g. HAL3.x open as HAL2.x) are not supported yet.
            ALOGE("Invalid camera HAL version %x: HAL %x device can only be"
                    " opened as HAL %x device", halVersion, deviceVersion,
                    CAMERA_DEVICE_API_VERSION_1_0);
            return INVALID_OPERATION;
        }
    }
    return NO_ERROR;
}

其中就是创建一个Client对象,由于此处分析的是Camera API2.0,其HAL的版本是3.0+,而Device的版本则其Device的版本即为3.0+,所以会创建一个CameraDeviceClient对象,至此,makeClient已经创建了client对象,并返回了,接着看它的初始化:

//CameraDeviceClient.cpp
status_t CameraDeviceClient::initialize(CameraModule *module)
{
    ATRACE_CALL();
    status_t res;
    //调用Camera2ClientBase的初始化函数来初始化CameraModule模块
    res = Camera2ClientBase::initialize(module);
    if (res != OK) {
        return res;
    }

    String8 threadName;
    //初始化FrameProcessor
    mFrameProcessor = new FrameProcessorBase(mDevice);
    threadName = String8::format("CDU-%d-FrameProc", mCameraId);
    mFrameProcessor->run(threadName.string());
    //并注册监听,监听的实现就在CameraDeviceClient类中
    mFrameProcessor->registerListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
            FRAME_PROCESSOR_LISTENER_MAX_ID, /*listener*/this,/*sendPartials*/true);
    return OK;
}

它会调用Camera2ClientBase的initialize方法来初始化,并且会初始化一个FrameProcessor来进行帧处理,主要是回调每一帧的ExtraResult到应用中,也就是3A相关的数据信息。而Camera1.0中各种Processor模块,即将数据打包处理后再返回到应用的模块都已经不存在,而Camera2.0中将由MediaRecorder、SurfaceView、ImageReader等来直接处理,总体来说效率更好。继续看initialize:

// Camera2ClientBase.cpp
template <typename TClientBase>
status_t Camera2ClientBase<TClientBase>::initialize(CameraModule *module) {
    ...
    //调用Device的initialie方法
    res = mDevice->initialize(module);
    ...
    res = mDevice->setNotifyCallback(this);
    return OK;
}

代码就是调用了Device的initialize方法,此处的Device是在Camera2ClientBase的构造函数中创建的:

// Camera2ClientBase.cpp
template <typename TClientBase>
Camera2ClientBase<TClientBase>::Camera2ClientBase(const sp<CameraService>& cameraService,
        const sp<TCamCallbacks>& remoteCallback,const String16& clientPackageName,
        int cameraId,int cameraFacing,int clientPid,uid_t clientUid,int servicePid):
        TClientBase(cameraService, remoteCallback, clientPackageName,cameraId, cameraFacing, 
        clientPid, clientUid, servicePid),mSharedCameraCallbacks(remoteCallback),
        mDeviceVersion(cameraService->getDeviceVersion(cameraId))
{
    ...
    mInitialClientPid = clientPid;
    mDevice = CameraDeviceFactory::createDevice(cameraId);
    ...
}

目前Camera API是2.0,而Device的API已经是3.0+了,继续看CameraDeviceFactory的createDevice方法:

// CameraDeviceFactory.cpp
sp<CameraDeviceBase> CameraDeviceFactory::createDevice(int cameraId) {

    sp<CameraService> svc = sService.promote();
    ...
    int deviceVersion = svc->getDeviceVersion(cameraId, /*facing*/NULL);

    sp<CameraDeviceBase> device;

    switch (deviceVersion) {
        case CAMERA_DEVICE_API_VERSION_2_0:
        case CAMERA_DEVICE_API_VERSION_2_1:
            device = new Camera2Device(cameraId);
            break;
        case CAMERA_DEVICE_API_VERSION_3_0:
        case CAMERA_DEVICE_API_VERSION_3_1:
        case CAMERA_DEVICE_API_VERSION_3_2:
        case CAMERA_DEVICE_API_VERSION_3_3:
            device = new Camera3Device(cameraId);
            break;
        default:
            ALOGE("%s: Camera %d: Unknown HAL device version %d",
                  __FUNCTION__, cameraId, deviceVersion);
            device = NULL;
            break;
    }
    return device;
}

很显然,它将会创建一个Camera3Device对象,所以,Device的initialize就是调用了Camera3Device的initialize方法:

// Camera3Device.cpp
status_t Camera3Device::initialize(CameraModule *module)
{
    ...
    camera3_device_t *device;
    //打开Camera HAL层的Deivce
    res = module->open(deviceName.string(),
            reinterpret_cast<hw_device_t**>(&device));
    ...

    //交叉检查Device的版本
    if (device->common.version < CAMERA_DEVICE_API_VERSION_3_0) {
        SET_ERR_L("Could not open camera: "
                "Camera device should be at least %x, reports %x instead",
                CAMERA_DEVICE_API_VERSION_3_0,
                device->common.version);
        device->common.close(&device->common);
        return BAD_VALUE;
    }
    ...

    //调用回调函数来进行初始化,即调用打开Device的initialize方法来进行初始化
    res = device->ops->initialize(device, this);
    ...

    //启动请求队列线程
    mRequestThread = new RequestThread(this, mStatusTracker, device, aeLockAvailable);
    res = mRequestThread->run(String8::format("C3Dev-%d-ReqQueue", mId).string());
    if (res != OK) {
        SET_ERR_L("Unable to start request queue thread: %s (%d)",
                strerror(-res), res);
        device->common.close(&device->common);
        mRequestThread.clear();
        return res;
    }
    ...
    //返回初始成功
    return OK;
}

首先以来HAL框架打开并获得相应的Device对象,然后再回调此对象的initialize方法进行初始化,最后再启动RequestThread等线程,并返回initialize成功。至此Camera API2.0下的初始化过程就分析结束了。框架层的初始化时序图如下:

你可能感兴趣的:(源码,android,初始化,Camera,API2-0)