Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2163733
  • 博文数量: 374
  • 博客积分: 7276
  • 博客等级: 少将
  • 技术积分: 5669
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-06 16:35
文章分类

全部博文(374)

文章存档

2013年(23)

2012年(153)

2011年(198)

分类:

2013-01-03 22:20:07

    Camera子系统采用C/S架构,客户端和服务端在两个不同的进程当中,它们使用android中的binder机制进行通信,本系列文章将从Android Camera应用程序到硬件抽象的实现一步一步对照相机系统进行分析,首先从CameraService初始化过程着手,然后从上层APP打开照相机->进行preview->拍照以及聚焦等功能的实现全面的学习照相机子系统

1 CameraService初始化过程

    frameworks/av/media/mediaserverMain_mediaserver.cpp,

    CameraServiceMediaServer中初始化,下面代码是MediaServermain函数,在该函数中初始化照相机服务

点击(此处)折叠或打开

  1. int main(int argc, char** argv)

  2. {

  3.     sp<ProcessState> proc(ProcessState::self());

  4.     sp<IServiceManager> sm = defaultServiceManager();

  5.         .................

  6.     CameraService::instantiate();

  7.         ............

  8.     IPCThreadState::self()->joinThreadPool();

  9. }

    CameraService中的instantiate方法用来创建CameraService实例,并进行相应的初始化,这个函数定义在它的父类BinderService中:frameworks/native/include/binder/BinderService.h,替换之后见如下代码:

点击(此处)折叠或打开

  1. class BinderService

  2. {

  3. public:

  4.     static status_t publish(bool allowIsolated = false) {

  5.         sp<IServiceManager> sm(defaultServiceManager());

  6.         return sm->addService(String16(CameraService::getServiceName()),
  7.                             new CameraService(), allowIsolated);

  8.     }

  9.     ...................

  10.     static void instantiate() { publish(); }

  11.     ...................

  12. };

    相机服务的初始化过程首先是创建CameraService实例,然后将其注册到ServiceManager,关于它的启动是发生在init.rc,通过media_server来启动CameraService,具体代码如下:

system/rootdir/init.rc

点击(此处)折叠或打开

  1. service servicemanager /system/bin/servicemanager
  2.     class core
  3.     user system
  4.     group system
  5.     critical
  6.     onrestart restart zygote
  7.     onrestart restart media
  8.     onrestart restart surfaceflinger
  9.     onrestart restart drm

  10. service media /system/bin/mediaserver
  11.     class main
  12.     user media
  13.     group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc
  14.     ioprio rt 4

    在cameraService注册以及启动过程中cameraService自身会执行一些初始化的工作,主要涉及到如下工作

点击(此处)折叠或打开

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

  2. static CameraService *gCameraService;

  3. CameraService::CameraService()
  4. :mSoundRef(0), mModule(0)
  5. {
  6.     ALOGI("CameraService started (pid=%d)", getpid());
  7.     gCameraService = this;
  8. }

  9. void CameraService::onFirstRef()
  10. {
  11.     BnCameraService::onFirstRef();

  12.     if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
  13.                 (const hw_module_t **)&mModule) < 0) {
  14.         ALOGE("Could not load camera HAL module");
  15.         mNumberOfCameras = 0;
  16.     }
  17.     else {/*最大支持两个摄像头*/
  18.         mNumberOfCameras = mModule->get_number_of_cameras();
  19.         if (mNumberOfCameras > MAX_CAMERAS) {
  20.             ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
  21.                     mNumberOfCameras, MAX_CAMERAS);
  22.             mNumberOfCameras = MAX_CAMERAS;
  23.         }
  24.         for (int i = 0; i < mNumberOfCameras; i++) {
  25.             setCameraFree(i);
  26.         }
  27.     }
  28. }

    在上述初始化代码中,先通过调用HAL硬件抽象层库,获取支持的摄像头个数并保存到mNumberOfCameras

2 应用程序链接相机服务过程

     camera应用程序启动的时候首先会和CameraService建立连接,camera应用程序代码就不分析了,下面这副图是一个简单的流程图,画得有点丑

2-1:照相机应用程序启动流程图

    从上面的流程图我们可以看出在请求服务的过程中多出用到了应用框架层的camera,该类定义在 frameworks/base/core/java/android/hardware/Camera.java文件当中,这一个类正是Camera子系统中APP层和JNI层交换的接口,它对上为应用程序提供了各种操作Camera的方法,向下访问JNI实现它自身的接口Camera类定义如下:

点击(此处)折叠或打开

  1. public class Camera {
  2.     public static Camera open(int cameraId) {

  3.         return new Camera(cameraId);

  4.     }



  5.     Camera(int cameraId) {

  6.         .................

  7.      Looper looper;
  8.         if ((looper = Looper.myLooper()) != null) {
  9.             mEventHandler = new EventHandler(this, looper);
  10.         } else if ((looper = Looper.getMainLooper()) != null) {
  11.             mEventHandler = new EventHandler(this, looper);
  12.         } else {
  13.             mEventHandler = null;
  14.         }
  15.      native_setup(new WeakReference<Camera>(this), cameraId);

  16.     }
  17. }

    在分析框架源码之前,先让我们了解一下应用程序请求服务以及服务处理示意图:

2-2:照相机服务请求示意图

接下来按照上面5个步骤来分析具体的源码,其中地一个步骤的源码在上一步中已解释(2)Camera open(int cameraId)方法调用native_setup本地方法,其中native_setup本地方法在JNI层被注册成如下方法:

点击(此处)折叠或打开

  1. frameworks/base/core/jni/android_hardware_Camera.cpp
  2. static JNINativeMethod camMethods[] = {
  3.   { "native_setup",
  4.     "(Ljava/lang/Object;I)V",
  5.     (void*)android_hardware_Camera_native_setup },/*通过Camera.cpp连接CameraService*/
  6.     …...
  7. };

(3)native_setup函数通过JNI调用android_hardware_Camera_native_setup函数,该函数的实现如下://通过android_hardware_Camera_native_setup请求CameraService

点击(此处)折叠或打开

  1. static void android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz,
  2.     jobject weak_this, jint cameraId)
  3. {
  4.     sp<Camera> camera = Camera::connect(cameraId);

  5.     if (camera == NULL) {
  6.         jniThrowRuntimeException(env, "Fail to connect to camera service");
  7.         return;
  8.     }

  9.     // make sure camera hardware is alive 还记得前面的初始化?
  10.     if (camera->getStatus() != NO_ERROR) {
  11.         jniThrowRuntimeException(env, "Camera initialization failed");
  12.         return;
  13.     }

  14.     jclass clazz = env->GetObjectClass(thiz);
  15.     if (clazz == NULL) {
  16.         jniThrowRuntimeException(env, "Can't find android/hardware/Camera");
  17.         return;
  18.     }

  19.     // We use a weak reference so the Camera object can be garbage collected.
  20.     // The reference is only used as a proxy for callbacks.
  21.     sp<JNICameraContext> context = new JNICameraContext(env, weak_this, clazz, camera);
  22.     context->incStrong(thiz);
  23.     camera->setListener(context);
  24.     //将这一步骤返回的BpCameraClient返回到JAVA应用程序框架
  25.     // save context in opaque field
  26.     env->SetIntField(thiz, fields.context, (int)context.get());
  27. }

(4)android_hardware_Camera_native_setup通过调用Camera::connect(int cameraId)函数请求连接服务。frameworks/av/camera/camera.cpp

点击(此处)折叠或打开

  1. sp<Camera> Camera::connect(int cameraId)
  2. {
  3.     ALOGV("connect");
  4.     sp<Camera> c = new Camera();//BnCameraClient
  5.     const sp<ICameraService>& cs = getCameraService();//return BpCameraService
  6.     if (cs != 0) {//Used for processing all kinds of events
  7.         c->mCamera = cs->connect(c, cameraId);//return
  8.     }
  9.     if (c->mCamera != 0) {
  10.         c->mCamera->asBinder()->linkToDeath(c);
  11.         c->mStatus = NO_ERROR;
  12.     } else {
  13.         c.clear();
  14.     }
  15.     return c;
  16. }

(5)Camera::connect(int cameraId)函数首先向ServiceManager获取Camera服务信息,并生成CameraService服务代理BpCameraService,然后通过Binder通信发送CONNECT命令,BnCameraService收到CONNECT命令后调用CameraServiceconnect()成员函数来做相应的处理,接下来我们就分析CameraServiceconnect()成员函数,注意在这一步骤中首先new了一个Camera本地实例,这个Camera类是BnCameraClient的子类,在调用BpCameraService::connect的时候我们将新生成的Camera做为参数传递给了CameraService.我们先来看BpCameraServiceconnect函数

点击(此处)折叠或打开

  1. class BpCameraService: public BpInterface<ICameraService>
  2. {
  3. public:
  4.     // connect to camera service
  5.     virtual sp<ICamera> connect(const sp<ICameraClient>& cameraClient, int cameraId)
  6.     {
  7.         Parcel data, reply;
  8.         data.writeInterfaceToken(ICameraService::getInterfaceDescriptor());
  9.         data.writeStrongBinder(cameraClient->asBinder());//转换成IBinder类型
  10.         data.writeInt32(cameraId);
  11.         remote()->transact(BnCameraService::CONNECT, data, &reply);
  12.         return interface_cast<ICamera>(reply.readStrongBinder());//BpCamera
  13.     }
  14. };

    首先将我们传递过来的Camera对象转换成IBinder类型,然后由BnCameraService去响应该连接,最后就是等待服务端返回,如果成功这里为我们生成一个BpCamera实例,怎么来的下面继续分析,接收服务命令的代码段如下:

点击(此处)折叠或打开

  1. status_t BnCameraService::onTransact(
  2.     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
  3. {
  4.     switch(code) {

  5.         case CONNECT: {
  6.             CHECK_INTERFACE(ICameraService, data, reply);//
  7.             sp<ICameraClient> cameraClient =//(a)
  8.                  interface_cast<ICameraClient>(data.readStrongBinder());
  9.          //return Client 继承BnCamera
  10.             sp<ICamera> camera = connect(cameraClient, data.readInt32());//(b)
  11.             reply->writeStrongBinder(camera->asBinder());//(c)
  12.             return NO_ERROR;
  13.         } break;
  14.         default:
  15.             return BBinder::onTransact(code, data, reply, flags);
  16.     }
  17. }

    服务端接到CONNECT命令之后开始进行一系列的类型转换,先看代码段(a)还记得之前我们传递过来的是Camera实例,Camera继承了BnCameraClient,所以在(a),使用CameraBinder对象为我们生成了Camera服务代理BpCameraClient实例

    (b)将生成的BpCameraClient对象作为参数打包到CameraServiceconnect()函数中,至于这个connect函数做了什么,先不管.先看(c)

    (c)将在(b)中返回的实例对象以IBinder的形式返回,现在再回到BpCameraService::connect函数的最后一句return interface_cast(reply.readStrongBinder()),是不是明白了?如果在(c)中成功创建了一个Client实例对象,(ClientBnCamera的子类),那么在BpCameraService::connect函数中是不是会为我们返回一个BpCamera对象?yes!为了验证我们来分析CameraServiceconnect()成员函数frameworks/av/services/camera/libcameraservice/CameraService.cpp

点击(此处)折叠或打开

  1. sp<ICamera> CameraService::connect(
  2.         const sp<ICameraClient>& cameraClient, int cameraId) {
  3.     int callingPid = getCallingPid();

  4.     LOG1("CameraService::connect E (pid %d, id %d)", callingPid, cameraId);

  5.     if (!mModule) {/*在服务初始化的时候就已经获得了*/
  6.         ALOGE("Camera HAL module not loaded");
  7.         return NULL;
  8.     }

  9.     sp<Client> client;
  10.     if (cameraId < 0 || cameraId >= mNumberOfCameras) {
  11.         ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
  12.             callingPid, cameraId);
  13.         return NULL;
  14.     }

  15.     char value[PROPERTY_VALUE_MAX];
  16.     /*策略相关*/
  17.     property_get("sys.secpolicy.camera.disabled", value, "0");
  18.     if (strcmp(value, "1") == 0) {
  19.         // Camera is disabled by DevicePolicyManager.
  20.         ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
  21.         return NULL;
  22.     }

  23.     Mutex::Autolock lock(mServiceLock);
  24.     /*这是CameraService类中的一个成员变量是用来记录摄像头设备的,并且
  25.      *它是一个数组wp<Client> mClient[MAX_CAMERAS];每一个设备都对应一个Client
  26.      */
  27.     if (mClient[cameraId] != 0) {//第一次来的是应该是为空的,所以不会走这条分支
  28.         client = mClient[cameraId].promote();
  29.         if (client != 0) {
  30.             if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
  31.                 LOG1("CameraService::connect X (pid %d) (the same client)",
  32.                      callingPid);
  33.                 return client;
  34.             } else {
  35.                 ALOGW("CameraService::connect X (pid %d) rejected
  36.                                 (existing client).",callingPid);
  37.                 return NULL;
  38.             }
  39.         }
  40.         mClient[cameraId].clear();
  41.     }

  42.     if (mBusy[cameraId]) {/*如果这设备ID处于忙状态*/
  43.         ALOGW("CameraService::connect X (pid %d) rejected"
  44.                 " (camera %d is still busy).", callingPid, cameraId);
  45.         return NULL;
  46.     }
  47.     /*这个结构是硬件抽象范畴的,里面包含了一些基本信息
  48.      * 其中facing描述前置还是后置
  49.      * orientation 用来描述image方向
  50.      * device_version用来描述HAL的版本
  51.      */
  52.     struct camera_info info;
  53.     if (mModule->get_camera_info(cameraId, &info) != OK) {
  54.         ALOGE("Invalid camera id %d", cameraId);
  55.         return NULL;
  56.     }

  57.     int deviceVersion;
  58.     if (mModule->common.module_api_version == CAMERA_MODULE_API_VERSION_2_0) {
  59.         deviceVersion = info.device_version;
  60.     } else {
  61.         deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
  62.     }
  63.     /*根据HAL不同API的版本创建不同的client实例,在之前版本中不是这样的,这是4.2的变化*/
  64.     switch(deviceVersion) {
  65.       case CAMERA_DEVICE_API_VERSION_1_0:
  66.         client = new CameraClient(this, cameraClient, cameraId,
  67.                 info.facing, callingPid, getpid());
  68.         break;
  69.       case CAMERA_DEVICE_API_VERSION_2_0://for 4.2
  70.         client = new Camera2Client(this, cameraClient, cameraId,
  71.                 info.facing, callingPid, getpid());
  72.         break;
  73.       default:
  74.         ALOGE("Unknown camera device HAL version: %d", deviceVersion);
  75.         return NULL;
  76.     }
  77.     /*初始化camera_module_t *module*/
  78.     if (client->initialize(mModule) != OK) {
  79.         return NULL;
  80.     }

  81.     cameraClient->asBinder()->linkToDeath(this);
  82.     //最后将创建的CameraClient或Camera2Client实例保存到mClient[MAX_CAMERAS]数组当中去
  83.     //mClient[MAX_CAMERAS]数组是CameraService类中的成员变量
  84.     mClient[cameraId] = client;//every camera is a Client class
  85.     LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, getpid());
  86.     return client;/*最后返回*/
  87. }

    首先通过该函数我们可以验证上面的(c)观点,通过CameraService生成CameraService::Client服务代理BpCamera,下面看看Client类之间的关系图

2-2:照相机服务请求示意图2

阅读(5410) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~