Chinaunix首页 | 论坛 | 博客
  • 博客访问: 405394
  • 博文数量: 53
  • 博客积分: 1910
  • 博客等级: 中尉
  • 技术积分: 1130
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-10 14:56
文章分类

全部博文(53)

文章存档

2013年(1)

2012年(17)

2011年(33)

2010年(2)

分类: 嵌入式

2012-07-12 22:48:00

一. 3大接口和1个共享内存
    ISurfaceComposer, ISurfaceComposerClient,ISurface,SharedClient
 
  1. ISurfaceComposer (ISurfaceComposer.h)
    主要接口:
    /* retrieve the control block */
    virtual sp getCblk() const = 0;
    /* [un]freeze display. requires ACCESS_SURFACE_FLINGER permission */
    virtual status_t freezeDisplay(DisplayID dpy, uint32_t flags) = 0;
    virtual status_t unfreezeDisplay(DisplayID dpy, uint32_t flags) = 0;
    这两个接口应该和 earlysuspend时 关闭屏幕相关
    /* create connection with surface flinger, requires
     * ACCESS_SURFACE_FLINGER permission
     */
    virtual sp createConnection() = 0;
    建立与SurfaceFlinger service 的连接,并获得1个ISurfaceComposerClient
    接口
 
  2. ISurfaceComposerClient  (ISurfaceComposerClient.h)
    最重要的两个接口就是创建 和释放Surface
    /* Requires ACCESS_SURFACE_FLINGER permission
     */
    virtual sp createSurface( surface_data_t* data,
     int pid,const String8& name, DisplayID display,uint32_t w,
     uint32_t h, PixelFormat format, uint32_t flags) = 0;
    /* Requires ACCESS_SURFACE_FLINGER permission
     */
    virtual status_t    destroySurface(SurfaceID sid) = 0;
    
    为什么不在ISurfaceComposer中创建surface ,而是通过连接
    ISurfaceComposer获得ISurfaceComposerClient 来创建的原因在于
    在SurfaceFlinger service端可以有多个client 来连接service,
    通过类class Client : public BnSurfaceComposerClient来表示
    一个client连接
    通过 sp SurfaceFlinger::createConnection()
    可以看到每次通过ISurfaceComposer创建连接在service 端就会执行下面代码:
    sp client(new Client(this)); 
    返回时转换成父类指针,ISurfaceComposerClient

    service          -|-   client
    class Client     -|-   class  SurfaceComposerClient
 
    其中createSurface 接口在service 端的实现在(SurfaceFlinger.cpp):
    sp SurfaceFlinger::createSurface(const sp& client, int pid,
        const String8& name, ISurfaceComposerClient::surface_data_t* params,
        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
        uint32_t flags)
    它根据layer的类型(normal,dim,blur)来创建 sp layer;
    然后通过LayerBaseClient::getSurface->LayerBaseClient::createSurface
    new LayerBaseClient::Surface 对象返回,注意这个Surface是LayerBaseClient
    的嵌套类 :
    class Surface : public BnSurface  {
    从代码 new Surface(mFlinger, mIdentity,
            const_cast(this))
    可以看出创建的LayerBaseClient::Surface 时获得了mFlinger,且LayerBaseClient
    对象是他的owner
   
     LayerBaseClient 内置类Surface 是BnSurface的子类,
     所以这个内置类是LayerBaseClient用来做binder通讯
 
     这个图,网上找来的, 很好的表示了他们的关系:
 
 
  3. ISurface 接口
     主要接口如下:
     /*
     * requests a new buffer for the given index. If w, h, or format are
     * null the buffer is created with the parameters assigned to the
     * surface it is bound to. Otherwise the buffer's parameters are
     * set to those specified.
     */
    virtual sp requestBuffer(int bufferIdx,
    uint32_t w, uint32_t h, uint32_t format, uint32_t usage) = 0;
    virtual status_t registerBuffers(const BufferHeap& buffers) = 0;
    virtual void postBuffer(ssize_t offset) = 0; // one-way
    virtual void unregisterBuffers() = 0;
    virtual sp createOverlay(
       uint32_t w, uint32_t h, int32_t format, int32_t orientation) = 0;
    跟下BnSurface的onTransact 就可以了解具体在service端做了什么
    比如requestBuffer -> Layer::requestBuffer
    他就是用来请求2个GraphicBuffer中的1个,是由client端的Surface对象的
    dequeue()发起

    4. class SharedClient
    这个类是用来建立 client 和service 端的都可以访问的共享内存
    它被组合在SharedBufferClient 和SharedBufferServer的基类SharedBufferBase
    中,并在UserClient对象构造时被MemoryHeapBase 在ashmem 上创建
    class SharedClient 只有1个,但是内部的SharedBufferStack 最大可以有31个
    其中 volatile int32_t available; // number of dequeue-able buffers 
   
    相关ShareBuffer类的关系如下:
    SharedBufferClient ,SharedBufferServer 都是继承SharedBufferBase
    SharedBufferBase 包含SharedClient
    SharedClient 可容纳31个SharedBufferStack (对应到layer),
    SharedBufferStack 对应1个layer, 每个layer 对应2个buffer,front和back
    这样surfaceflinger中的threadloop 就会在这最大31个layer上循环,
    draw backbuff 中属于本层layer的需要画的部分
    然后切换到frontbuff ,通过post显示出来
    galloc 中的map就是用来把GraphicBuffer map到 client 端,让ui 在这个
    buffer 上画图

上面大概了解了这4个client 和service 进行通讯的通路,3个使用binder,1个使用
share memory
 
 
二. ISurfaceComposer
   该接口client 端相关的类有:
   * class ComposerService : public Singleton
     一个单实例类,用来获得SurfaceFlinger服务,就是BpSurfaceComposer
     SurfaceComposer的proxy
   * class SurfaceComposerClient : public RefBase
     该类包含的sp  mClient;
     该对象就是通过上面的BpSurfaceComposer 代理createConnection
     获得的BpSurfaceComposerClient,有了它就可以向flinger service
     发createSuface命令
   * class Composer : public Singleton
     Composer 是 SurfaceComposerClient 的容器
     SurfaceComposerClient 与 surfacefling 端连接上后,
     Composer::addClient(this); this 是SurfaceComposerClient对象
     它整理并发送每个layer的ComposerState
     其中相关函数openGlobalTransaction,closeGlobalTransaction
     实际由SurfaceComposerClient调用,但是Composer对所有的client
     都执行一次open 或者close Transaction

   该接口Service 端相关的类有:
   * class BnSurfaceComposer : public BnInterface
     处理BpSurfaceComposer 发来的
     CREATE_CONNECTION,
     CREATE_CLIENT_CONNECTION,
     SET_ORIENTATION,
     FREEZE_DISPLAY,
     UNFREEZE_DISPLAY, 等命令
   接下通过 SurfaceSession_init (android_view_Surface.cpp)
   来看下整个过程:
   *   sp client = new SurfaceComposerClient
    
   * void SurfaceComposerClient::onFirstRef()具体代码如下:

点击(此处)折叠或打开

  1. void SurfaceComposerClient::onFirstRef()
  2. {
  3.  /* class ISurfaceComposer : public IInterface */
  4.     sp<ISurfaceComposer> sm(getComposerService() );
  5. /* getComposerService 返回BpSurfaceComposer */
  6. /* ComposerService::getComposerService()
  7.       -> return ComposerService::getInstance().mComposerService;
  8.       注意 ComposerService::ComposerService() 的构造 */
  9. /*
  10. 上面声明了一个ISurfaceComposer 的sp 强指针,
  11. 根据sp ISurfaceComposer 内部的指针指向BpSurfaceComposer对象
  12. */
  13.    
  14. /* 到这里 sp<ISurfaceComposer> mComposerService;
  15.    已经在其构造函数中通过
  16.    getService("SurfaceFlinger", &mComposerService) 获得了*/
  17. /* 构造 调用的getService如下,访问的是ServiceManager
  18. template<typename INTERFACE>
  19. status_t getService(const String16& name, sp<INTERFACE>* outService)
  20. {
  21.     const sp<IServiceManager> sm = defaultServiceManager();
  22.     if (sm != NULL) {
  23.         *outService = interface_cast<INTERFACE>(sm->getService(name));
  24.         if ((*outService) != NULL) return NO_ERROR;
  25.     }
  26.     return NAME_NOT_FOUND;
  27. }
  28. */
  29.    
  30.     if (sm != 0) {
  31.         sp<ISurfaceComposerClient> conn = sm->createConnection();
  32. /* BpSurfaceComposer::createConnection 连接 service ,
  33.    返回ISurfaceComposerClient !!! */
  34. /* 虽然是sp<ISurfaceComposer> 强指针,
  35.    实际call 到子类BpSurfaceComposer 的createConnection 如下:
  36.  sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
  37. {
  38.     sp<ISurfaceComposerClient> bclient;
  39.     sp<Client> client(new Client(this));
  40.     status_t err = client->initCheck();
  41.     if (err == NO_ERROR) {
  42.         bclient = client;
  43.     }
  44.     return bclient;
  45. }
  46. */

  47. /* 到这里返回ISurfaceComposerClient 指针指向BpSurfaceComposerClient
  48.    与 BnSurfaceComposerClient 连接上了 */
  49.   
  50.         if (conn != 0) {
  51.             mClient = conn;
  52.      /* 返回ISurfaceComposerClient 指针指向
  53.        BpSurfaceComposerClient 并保存到SurfaceComposerClient
  54.        的成员mClient */
  55.             Composer::addClient(this);
  56.  /* SurfaceComposerClient this , composer singleton 中
  57.     SortedVector< wp<SurfaceComposerClient> > mActiveConnections;
  58.     的向量数组用来存放SurfaceComposerClient */
  59.             mPrebuiltLayerState = new layer_state_t;
  60.             mStatus = NO_ERROR;
  61.         }
  62.     }
  63. }
 

  看下ComposerService的构造函数,只会执行1次

点击(此处)折叠或打开

  1. ComposerService::ComposerService()
  2. : Singleton<ComposerService>() {
  3.     const String16 name("SurfaceFlinger");
  4. /* 这个getService 是IServiceManager.h中的全局模板函数,
  5.   status_t getService(const String16& name, sp<INTERFACE>* outService)
  6.   下面调用时传入参数是sp<ISurfaceComposer> mComposerService;
  7.   所以模板展开时的<INTERFACE> => < ISurfaceComposer>
  8. */
  9.     while (getService(name, &mComposerService) != NO_ERROR) {
  10.     /* 从service manager 获得SurfaceFlinger service !!! */
  11.     /* getService是返回的一个相关代理的Binder,
  12.  通过interface_cast方法将这个binder转换为BpXXXService。
  13.  所以得到的是bp。客户端只能看得到代理类
  14.        
  15.        这个SurfaceFlinger 是在
  16.           => sm->addService(String16(SurfaceFlinger::getServiceName()),
  17.      new SurfaceFlinger()) 注册到 Service
  18.             注意 flatten_binder 中的代码
  19. */

  20.         usleep(250000);
  21.     }
  22.   // 获取共享内存块 sp<IMemoryHeap> SurfaceFlinger::getCblk() const
  23.   // {
  24.   // return mServerHeap;
  25.   //}
  26.     mServerCblkMemory = mComposerService->getCblk();
  27.    //获取共享内存块基地址,这个是display的共享内存块不是shareclient 部分的
  28.     mServerCblk = static_cast<surface_flinger_cblk_t volatile *>(
  29.             mServerCblkMemory->getBase());
  30. }
 
    对应到service(SurfaceFlinger.cpp)端的createConnection如下:

点击(此处)折叠或打开

  1. sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
  2. /* 现在在Service 端,就是前面的client向ISurfaceComposer 请求的连接,
  3. 返回指向Client:BnSurfaceComposerClient 对象的ISurfaceComposerClient 指针*/
  4. {
  5.     sp<ISurfaceComposerClient> bclient;
  6.     sp<Client> client(new Client(this));
  7.     /* new 一个Client 类,class Client : public BnSurfaceComposerClient*/
  8.     /* 1. 在createConnection阶段,SurfaceFlinger创建Client对象
  9.        2. Client 对象通过构造赋值mFlinger(flinger),将SurfaceFlinger和
  10.            Client 对象关联起来
  11.     */

  12.     status_t err = client->initCheck();
  13. /* class BnSurfaceComposerClient : public BnInterface<ISurfaceComposerClient> */
  14.     if (err == NO_ERROR) {
  15.         bclient = client;
  16.     }
  17.     return bclient; /* 返回时转换成父类指针,ISurfaceComposerClient */
  18. }

   到这里new了一个SurfaceComposerClient的对象,并且获得BpSurfaceComposerClient
 
三. ISurfaceComposerClient
   1. 该接口client 端相关的类有:
     * class SurfaceControl : public RefBase
       包含:
       sp   mClient;
       sp                mSurface;                      
       /* 一个已经创建的并返回给client的ISurface ,由surfaceControl管理 */
      
        mutable sp         mSurfaceData;
       /* 这个Surface 需要到lock canvas 时通过getSurface()
          来生成 client Surface类对象!!! */
     
      * class ISurface : public IInterface 
        client 对应到 BpSurface
 
      ISurfaceComposerClient 创建surface 时,其实还没有创建client 端的Surface 对象
      要等等到lock canvas 中通过getSurface 来创建,这时候new Surface时构造
      中 获得SurfaceClient Singleton 类的mClient(SurfaceClient::getInstance()),
      然后再 createClientConnection ,再serivce 端分配共享块,
      这个client Surface 和service 端的layer对应,他们并不矛盾,因为共享块只分配1次
      所以SurfaceClient 是Singleton
     
      但是先列下该client Surface类:
      * class Surface : public
               EGLNativeBase
         包含:
        SurfaceClient&              mClient;                           
     /* 注意这个类和service 的userclient 相关
     在改类的构造中通过ISurfaceComposer调用createClientConnection
     然后service new UserClient
     建立前面说的那个最大31K 的ShareClient控制块
     */
       SharedBufferClient*         mSharedBufferClient;
       new SharedBufferClient 时通过 mClient.getSharedClient()
    
       将 下面 mControl地址 传给mSharedBufferClient
     * class SurfaceClient : public Singleton
        通过接口IMemoryHeap 获得Bp 端的31K layer control 共享块地址
        放到成员 SharedClient* mControl;
        用Singleton,因为共享块地址地址就1个
 

   2. 该接口service 端相关的类有:
      * class Client : public BnSurfaceComposerClient
        包含:
         DefaultKeyedVector< size_t, wp > mLayers;
        /* 可以有多个client ,每个client 又有多个layer , layer vector */
        sp mFlinger; 在Client 可以找到SurfaceFlinger
   
      * class LayerBase : public RefBase
 
      * class LayerBaseClient : public LayerBase
        包含: 内置类 class Surface : public BnSurface
 
      * class Layer : public LayerBaseClient
        Layer 是LayerBaseClient 的子类
        有内置类:   
          class SurfaceLayer : public LayerBaseClient::Surface , 
          class ClientRef , 
          class BufferManager
        这个就是nomal layer,
        其他class LayerBlur : public LayerBaseClient就不分析了
        这个类比较复杂,后续代码中再讨论

   3. 通过 Surface_init(android_view_Surface.cpp)
      分析下在这步Service 和client 如何实现CreatSurface
 
      * SurfaceComposerClient::createSurface 代码如下:

点击(此处)折叠或打开

  1. sp<SurfaceControl> SurfaceComposerClient::createSurface(
  2.         int pid, const String8& name,
  3.         DisplayID display, uint32_t w,
  4.         uint32_t h, PixelFormat format,
  5.         uint32_t flags)
  6. {
  7.     sp<SurfaceControl> result;
  8.     if (mStatus == NO_ERROR) {
  9.         ISurfaceComposerClient::surface_data_t data;
  10. /* mClient 是 sm->createConnection() (BpSurfaceComposer::createConnection)
  11.    返回ISurfaceComposerClient 指针指向 BpSurfaceComposerClient
  12.    且它与 BnSurfaceComposerClient 连接上了
  13.     call BpSurfaceComposerClient createSurface ,binder 通讯层面上的*/
  14.         /* BpSurfaceComposerClient 层creatSurface ,binder 调用*/
  15.         sp<ISurface> surface = mClient->createSurface(&data, pid, name,
  16.                 display, w, h, format, flags);
  17.  /* 返回BpSurface !!! ,server端 已经创建了surface */
  18.         if (surface != 0) { /* BpSurface */
  19.     /*
  20.      并把返回的BpSurface和当前的SurfaceComposerClient
  21.      保存在SurfaceControl中, 然后返回此SurfaceControl
  22.     */
  23.             result = new SurfaceControl(this, surface, data, w, h, format,
  24.              flags);
  25.     /* 通过SurfaceControl 的构造函数: 传入
  26.     mClient(client), 就是this (SurfaceComposerClient)
  27.     mSurface(surface), 就是 BpSurface (ISurface)
  28.     */
  29.         }
  30.     }
  31.     return result;
  32. }
         client 端比较简单,到目前获得了ISurface 接口的代理类BpSurface,
  并且生成了SurfaceControl类,其实还看不出SurfaceControl目前的作用
  等到lock canvas 时 就要用到它的getSurface来建立C/S双方的shareclient
  时,就有用了
 
      * createSurface 的Service 端比较复杂先看下SurfaceFlinger.cpp 中:
 
      sp SurfaceFlinger::createSurface(const sp& client, int pid,
        const String8& name, ISurfaceComposerClient::surface_data_t* params,
        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
        uint32_t flags)
  
     都拿normal layer 说事:

     a.创建normal layer:
        normalLayer = createNormalSurface(client, d, w, h, flags, format);
         -> new Layer(this, display, client);  注意构造中init的成员变量
         -> getBuffer:
            layer 成员变量的init
            mSurface = new SurfaceLayer(mFlinger, this);  
 
     b.addClientLayer(client, layer);
       1. layer 加入到Client 对象的
          DefaultKeyedVector< size_t, wp > mLayers
       2. 按Z-order排序,加入到SurfaceFlinger 的State成员的layersSortedByZ
          mCurrentState.layersSortedByZ.add(layer);
 
     c. surfaceHandle = layer->getSurface();   
          注意surfaceflinger的createsurface ->
                               layer getSuface ->
                                layer createSurface -> 
          最后生成LayerBaseClient::Surface 内置类对象如下:
          new Surface(mFlinger, mIdentity, const_cast(this));
 
     d. mLayerMap.add(surfaceHandle->asBinder()/*BnSurface pointer*/,normalLayer);   
        这里将所有的创建的普通的Layer保存起来,以便Client Surface在请求实现Buffer时能够
        根据 Client Surface(BpSurface)找到对应的Layer!!!
 
      e. setTransactionFlags(eTransactionNeeded);  去触发 thread_loop event
      
      f.最后返回 surfaceHandle 就是BnSurface
 
    service端执行到这里时layer有了,但是3个内置类中只有Surface建立了,而clientRef
    BufferManager 中相关buffer的操作,在那里做的??? 下面ISuface部分继续看
  
四. ISuface  
    1. 该接口client 端相关的类有:
      *  class Surface:public EGLNativeBase
         该类对象包含在SurfaceControl的mutable sp mSurfaceData;
     
         该类内容丰富,主要有下面部分:
         struct SurfaceInfo 其中的bit就是buffer在client端的vaddr地址
 
         class BufferInfo 内置类
 
         SurfaceClient&  mClient;/* 注意这个类和userclient 相对应*/

         Vector< sp > mBuffers;/* GraphicBuffer 的vector,
         下面会讲如何获得它*/
 
         方法:
         static int dequeueBuffer(ANativeWindow* window,
                           android_native_buffer_t** buffer);
          static int cancelBuffer(ANativeWindow* window,
                           android_native_buffer_t* buffer);
      
     *  class SharedBufferClient : public SharedBufferBase
 
     *  class SurfaceClient : public Singleton
       这两个类和共享控制块相关
      
    2. 该接口Service 端相关的类有:
       class UserClient : public BnSurfaceComposerClient
 
    3. 通过 Surface_lockCanvas(android_view_Surface.cpp)
      分析下在这步Service 和client 如何实现buffer的管理
      a. 从sp SurfaceControl::getSurface()开始
          mSurfaceData = new Surface(const_cast(this));
 
      b. Surface 的构造如下:

点击(此处)折叠或打开

  1. Surface::Surface(const sp<SurfaceControl>& surface) /* getsurface */
  2.     : mBufferMapper(GraphicBufferMapper::get()),
  3.       mClient(SurfaceClient::getInstance()),
  4.       mSharedBufferClient(NULL),
  5.       mInitCheck(NO_INIT),
  6.       mSurface(surface->mSurface),
  7.       mIdentity(surface->mIdentity),
  8.       mFormat(surface->mFormat), mFlags(surface->mFlags),
  9.       mWidth(surface->mWidth), mHeight(surface->mHeight)
  10. {
  11.     init(); /* 在构造中init */
  12. }
      mBufferMapper 也是个单实例类,获得它是为了访问galloc的lock,unlock
      mClient 是单实例类SurfaceClient的对象,前面已经讲过SurfaceClient
      是用ISurfaceComposer来createClientConnection(在service端建立
      shareclient 共享控制块的),每个SurfaceControl 只有1个
      所以只需要第1次SurfaceClient 类对象建立时做1次,所以这里用Singleton
 
      mSurface (surface->mSurface) 将SurfaceControl获得的ISurface 传给Surface
 
      mIdentity(surface->mIdentity) SurfaceControl 和其包含的Surface
      的Identity 一样,所以SurfaceControl与Surface是1对1关系

    c. 看下SurfaceClient 类对象的mClient的构造:

点击(此处)折叠或打开

  1. SurfaceClient()
  2.         : Singleton<SurfaceClient>(), mStatus(NO_INIT)
  3.     {
  4.         sp<ISurfaceComposer> sf(ComposerService::getComposerService());
  5.         mComposerService = sf;
  6.         mClient = sf->createClientConnection();
  7.  /* service 端的serclient 在这时创建,下面具体再看*/
  8.         if (mClient != NULL) {
  9.             mControlMemory = mClient->getControlBlock();
  10.             if (mControlMemory != NULL) {
  11.                 mControl = static_cast<SharedClient *>(
  12.                         mControlMemory->getBase());
  13. /* 在这里获得Bp 端的31K layer control 共享块地址 并放到SurfaceClient
  14.    成员 mControl 中去 */
  15.                 if (mControl) {
  16.                     mStatus = NO_ERROR;
  17.                 }
  18.             }
  19.         }
  20.     }
 
     d.  createClientConnection 在service端的代码:

点击(此处)折叠或打开

  1. sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection()
  2. {
  3.     sp<ISurfaceComposerClient> bclient;
  4.     /* 一样都是ISurfaceComposerClient 接口*/
  5.     sp<UserClient> client(new UserClient(this));
  6.     /* 在这里new 一个UserClient ,接下来看其构造*/
  7.     status_t err = client->initCheck();
  8.     if (err == NO_ERROR) {
  9.         bclient = client;
  10.     }
  11.     return bclient;
  12. }

     e. Service 端的UserClient的构造:

点击(此处)折叠或打开

  1. UserClient::UserClient(const sp<SurfaceFlinger>& flinger)
  2.     : ctrlblk(0), mBitmap(0), mFlinger(flinger)
  3. {
  4.     const int pgsize = getpagesize();
  5.     const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1));
  6.     mCblkHeap = new MemoryHeapBase(cblksize, 0,
  7.             "SurfaceFlinger Client control-block");
  8.     /* 31 layer 的control blk 在UserClient 中创建*/
  9.     ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
  10.     if (ctrlblk) { // construct the shared structure in-place.
  11.         new(ctrlblk) SharedClient;
  12. /* UserClient 中成员 SharedClient* ctrlblk, pointer to this client's control block ;
  13.    到这里 UserClient的成员 SharedClient* ctrlblk;获得了share memory 的地址 */
  14.     }
  15. }

   
     f. 回到Surface的init 继续:

点击(此处)折叠或打开

  1. void Surface::init()
  2. {
  3.    ......
  4.     if (mSurface != 0 && mClient.initCheck() == NO_ERROR) {
  5.         int32_t token = mClient.getTokenForSurface(mSurface);
  6.         if (token >= 0) {
  7.  /* client surface 类的init中new sharedbufferClient */
  8.             mSharedBufferClient = new SharedBufferClient(
  9.                     mClient.getSharedClient(), token, 2, mIdentity);
  10. /* SharedBufferClient 构造参数mClient.getSharedClient()
  11.    把前面SurfaceClient 中mContrl (控制块的client端map的地址)
  12.    传给它的Base class SharedBufferBase的成员mSharedClient
  13. */
  14.             mInitCheck = mClient.getSharedClient()->validate(token);
  15.      /* SharedBufferClient 装ShareBufferStack */
  16.         }
  17.     }
  18.  ......
     到这里 ShareClient 共享内存块建立了, ShareClient 的client 端
     的类SharedBufferClient 对象建立了,map share mem在client 端地址也有了
     但有两个问题:
      1.SharedBufferServer类在那里创建的?
      2.前面创建surface 时的layer 如何和ShareClient 扯上关系的?
    带着这两个问题看下上面init中的这句话:
     int32_t token = mClient.getTokenForSurface(mSurface);
     通过ISurfaceComposerClient到service 端执行下面函数:

点击(此处)折叠或打开

  1. ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const
  2. {
  3.     int32_t name = NAME_NOT_FOUND;
  4.     /* 根据ISurface 找到layer ,是否记得前面createSurface时创建layer时
  5.        加到一个ISurface和 layer对应的map的这句话:
  6.        mLayerMap.add(surfaceHandle->asBinder()/*BnSurface pointer*/
  7.             , normalLayer);
  8.     */
  9.     sp<Layer> layer(mFlinger->getLayer(sur));
  10.     if (layer == 0) return name;
  11.     /* 下面第1次肯定不成立,从来没有setToken,让它那里去get */
  12.     // if this layer already has a token, just return it
  13.     name = layer->getToken();
  14.     if ((name >= 0) && (layer->getClient() == this))
  15.         return name;
  16.     /* 走到这里*/
  17.     name = 0;
  18.     do {
  19.         int32_t mask = 1LU<<name;
  20.         if ((android_atomic_or(mask, &mBitmap) & mask) == 0) {
  21.  /* 有车位,赶紧占个位置,调用layer->setToken,注意参数
  22.    name 应该为0-31中某1个,UserClient有着落了 ,ctrlblk
  23.    前面Userclient 构造时通过
  24.    ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
  25.    也要传入
  26.    但是 layer对setToken只是挂个名,交给内置类ClientRef去做 SetToken
  27.    也不能说完全挂名,new ShareclientServer 还是由layer的setToken完成:
  28.    status_t Layer::setToken(const sp<UserClient>& userClient,
  29.            SharedClient* sharedClient, int32_t token)
  30.           {
  31.               sp<SharedBufferServer> lcblk = new SharedBufferServer(
  32.             sharedClient, token, mBufferManager.getDefaultBufferCount(),
  33.             getIdentity());
  34.             status_t err = mUserClientRef.setToken(userClient, lcblk, token);
  35.      ......
  36.     }
  37.  */
  38.             // we found and locked that name
  39.             status_t err = layer->setToken(
  40.                     const_cast<UserClient*>(this), ctrlblk, name);
  41.             if (err != NO_ERROR) {
  42.                 // free the name
  43.                 android_atomic_and(~mask, &mBitmap);
  44.                 name = err;
  45.             }
  46.             break;
  47.         }
  48.         if (++name >= SharedBufferStack::NUM_LAYERS_MAX)
  49.             name = NO_MEMORY;
  50.     } while(name >= 0);
  51.     //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)",
  52.     // sur->asBinder().get(), name, this, mBitmap);
  53.     return name;
  54. }
    跟到layer内置类ClientRef的setToken如下:

点击(此处)折叠或打开

  1. status_t Layer::ClientRef::setToken(const sp<UserClient>& uc,
  2.         const sp<SharedBufferServer>& sharedClient, int32_t token) {
  3.     Mutex::Autolock _l(mLock);
  4.     { // scope for strong mUserClient reference
  5.         sp<UserClient> userClient(mUserClient.promote());
  6.         if (mUserClient != 0 && mControlBlock != 0) {
  7.             mControlBlock->setStatus(NO_INIT);
  8.         }
  9.     }
  10.     mUserClient = uc;
  11.     mToken = token;
  12.     mControlBlock = sharedClient;
  13.   /* 其实也没做什么,设置ClientRef的mToken,为刚获得的name 号,
  14.      设置 ClientRef 的mUserClient
  15.      shareClient 就是 ShareClientServer的地址
  16.      看起来layer, token ,ShareClientServer
  17.        以后layer 层可以通过ClientRef内置类来获得这3个元素
  18.        到这里可知道layer通过ClientRef内置类与ShareClient扯上关系
  19.        ClientRef中的函数:
  20.         inline SharedBufferServer* get() const { return mControlBlock.get(); }
  21.        再次认同了这个说法
  22.     */

  23.     return NO_ERROR;
  24. }
 
  g.   Surface::init 的结束标志这getSurface 完成
    C/S 双方的shareClient ,client 的Surface和 Service的layer 都关联起来了
    回到开头的Surface_lockCanvas去看下面2句:
    Surface::SurfaceInfo info;
    status_t err = surface->lock(&info, &dirtyRegion);
    这个lock 操作就是为了为了获得这个info中的bits

    lock代码:(其中展开的函数用斜体)

点击(此处)折叠或打开

  1. status_t Surface::lock(SurfaceInfo* other, Region* dirtyIn, bool blocking)
  2. {
  3.     ......
  4.     ssize_t bufIdx = mSharedBufferClient->dequeue();
  5.     /* 这句也很关键,在这里面获得bufIdx ,看下该函数:
  6.     ssize_t SharedBufferClient::dequeue(){
  7.         DequeueCondition condition(this);
  8.     status_t err = waitForCondition(condition);
  9.     /* waitForCondition 判断并等待SharedBufferStack.available(最大=2)
  10.        不为0
  11.     */
  12.     if (err != NO_ERROR)
  13.         return ssize_t(err);
  14.     /* 跑到这里表示ShareBufferStack上有可用buffer */
  15.     DequeueUpdate update(this);
  16.     updateCondition( update );
  17.     /* 进入后DequeueUpdate 的update obj 调用重载的() operator,
  18.     android_atomic_dec(&stack.available)
  19.      将 available 递减 ,
  20.      
  21.      注意available 加1并不是在 unlockandpost中做的
  22.      看起来应该是在
  23.      thread loop 的 lockPageFlip 中
  24.      ssize_t buf = lcblk->retireAndLock();
  25.      那么是什么情况会导致available 没有被inc 回来导致available=0
  26.      然后
  27.      waitForCondition 时,没available的buffer可用,所以可能看到过这样的msg:
  28. W/SharedBufferStack( 2634): waitForCondition(LockCondition) timed out (identity=8, status=0). CPU may be pegged. trying again.
  29. W/SharedBufferStack( 2634): waitForCondition(LockCondition) timed out (identity=8, status=0). CPU may be pegged. trying again.
  30.      
  31.      */
  32.    
  33.     */
  34.     ......
  35.     android_native_buffer_t* out;
  36.     status_t err = dequeueBuffer(&out);
  37. /* 看下删节的dequeueBuffer
  38. int Surface::dequeueBuffer(android_native_buffer_t** buffer)
  39. {
  40.     ......
  41.     uint32_t w, h, format, usage;
  42.     if (needNewBuffer(bufIdx, &w, &h, &format, &usage)) {
  43.         err = getBufferLocked(bufIdx, w, h, format, usage);
  44.  /* 到这里new graphic buffer ,可能分析的是2.3.4
  45.    其他贴子上是在CreateSurface 时就new GraphicBuffer了
  46. 比如http://www.360doc.com/content/11/0722/11/11192_135158837.shtml
  47. 中图1
  48.  */
  49.         LOGE_IF(err, "getBufferLocked(%ld, %u, %u, %u, %08x) failed (%s)",
  50.                 bufIdx, w, h, format, usage, strerror(-err));
  51.         if (err == NO_ERROR) {
  52.             // reset the width/height with the what we get from the buffer
  53.             const sp<GraphicBuffer>& backBuffer(mBuffers[bufIdx]);
  54.      /* getBufferLocked 中已经把mBuffers的bufIdx对应的GraphicBuffer准备好了
  55.         mmap到client ,下面会再列下getBufferLocked的代码,具体看下就知道
  56.      */
  57.             mWidth = uint32_t(backBuffer->width);
  58.             mHeight = uint32_t(backBuffer->height);
  59.         }
  60.     }
  61.     ......
  62.     return err;
  63. }
  64. */
  65.     LOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
  66.     if (err == NO_ERROR) {
  67.         sp<GraphicBuffer> backBuffer(GraphicBuffer::getSelf(out));
  68.  /* 由out 构建GraphicBuffer 类对象backbuffer */
  69.         /* wait condition 测试*/
  70.         err = lockBuffer(backBuffer.get());
  71.  /*
  72.  注意这个lockcondtion 如下:
  73. bool SharedBufferClient::LockCondition::operator()() const {
  74.     // NOTE: if stack.head is messed up, we could crash the client
  75.     // or cause some drawing artifacts. This is okay, as long as it is
  76.     // limited to the client.
  77.     return (buf != stack.index[stack.head]);
  78. }
  79. 这个表示不能等于head,因为head总是用来做front的,back 总是用tail
  80. 不知道这个描述是否有问题
  81.  */

  82.         LOGE_IF(err, "lockBuffer (idx=%d) failed (%s)",
  83.                 getBufferIndex(backBuffer), strerror(-err));
  84.         if (err == NO_ERROR) {
  85.             const Rect bounds(backBuffer->width, backBuffer->height);
  86.             const Region boundsRegion(bounds);
  87.             Region scratch(boundsRegion);
  88.             Region& newDirtyRegion(dirtyIn ? *dirtyIn : scratch);
  89.             newDirtyRegion &= boundsRegion;
  90.             // figure out if we can copy the frontbuffer back
  91.             const sp<GraphicBuffer>& frontBuffer(mPostedBuffer);
  92.             const bool canCopyBack = (frontBuffer != 0 &&
  93.                     backBuffer->width == frontBuffer->width &&
  94.                     backBuffer->height == frontBuffer->height &&
  95.                     backBuffer->format == frontBuffer->format &&
  96.                     !(mFlags & ISurfaceComposer::eDestroyBackbuffer));
  97. /* 判断能够copy 的条件是否满足,前后size一样大,格式都一样时才copy*/
  98.             // the dirty region we report to surfaceflinger is the one
  99.             // given by the user (as opposed to the one *we* return to the
  100.             // user).
  101.             mDirtyRegion = newDirtyRegion;
  102.             if (canCopyBack) {
  103.                 // copy the area that is invalid and not repainted this round
  104.                 const Region copyback(mOldDirtyRegion.subtract(newDirtyRegion));
  105.                 if (!copyback.isEmpty())
  106.                     copyBlt(backBuffer, frontBuffer, copyback);
  107.       /* 把front copy 到back ,这样不用从头画了*/
  108.             } else {
  109.                 // if we can't copy-back anything, modify the user's dirty
  110.                 // region to make sure they redraw the whole buffer
  111.                 newDirtyRegion = boundsRegion;
  112.             }
  113.             // keep track of the are of the buffer that is "clean"
  114.             // (ie: that will be redrawn)
  115.             mOldDirtyRegion = newDirtyRegion;
  116.             void* vaddr;
  117.             status_t res = backBuffer->lock(
  118.                GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN,
  119.                newDirtyRegion.bounds(), &vaddr);
  120.             /* backBuffer 中取出它在client 端的vaddr !!! */
  121.             
  122.             LOGW_IF(res, "failed locking buffer (handle = %p)",
  123.                     backBuffer->handle);
  124.             mLockedBuffer = backBuffer;
  125.             other->w = backBuffer->width;
  126.             other->h = backBuffer->height;
  127.             other->s = backBuffer->stride;
  128.             other->usage = backBuffer->usage;
  129.             other->format = backBuffer->format;
  130.             other->bits = vaddr;
  131.      /* bits 就是surface buffer 的虚地址,vaddr 传给handle ->bits */
  132.         }
  133.     }
  134.     mApiLock.unlock();
  135.     return err;
  136. }
    最后回到static jobject Surface_lockCanvas
    看下其中代码:

点击(此处)折叠或打开

  1. status_t err = surface->lock(&info, &dirtyRegion);
  2.     /* 回来时info 中的bits已经有内容了*/
  3.     ......
  4.     if (info.w > 0 && info.h > 0) {
  5.         bitmap.setPixels(info.bits);
  6. /* Canvas的Bitmap设备设置了Client Surface的显示Buffer
  7. 为其Bitmap pixel存储空间。 设置bits 的地方在Surface::lock */
  8.     } else {
  9.    ......
    搞个地址画图 真是不容易!
lock canvas的sequnce图:
摘自
 
 

前面提到的 getBufferLocked 函数代码如下:

点击(此处)折叠或打开

  1. status_t Surface::getBufferLocked(int index,
  2.         uint32_t w, uint32_t h, uint32_t format, uint32_t usage) /* called by dequeueBuffer */
  3. {
  4.     sp<ISurface> s(mSurface);
  5.     if (s == 0) return NO_INIT;
  6.     status_t err = NO_MEMORY;
  7.     // free the current buffer
  8.     sp<GraphicBuffer>& currentBuffer(mBuffers.editItemAt(index));
  9.     /* currentBuffer 引用了mBuffers index 的那个 GraphicBuffer*/
  10.     if (currentBuffer != 0) {
  11.         getBufferMapper().unregisterBuffer(currentBuffer->handle);
  12.         currentBuffer.clear();
  13.     }
  14.     sp<GraphicBuffer> buffer = s->requestBuffer(index, w, h, format, usage);
  15. /* 调用到service 端的sp<GraphicBuffer> Layer::requestBuffer
  16.   返回时已经获得framebuffer mmap vadder 并放到了
  17.  GraphicBuffer 的base class android_native_buffer_t 的 handle中*/
  18.     ......
  19.     if (buffer != 0) { // this should never happen by construction
  20.         LOGE_IF(buffer->handle == NULL,
  21.                 "Surface (identity=%d) requestBuffer(%d, %u, %u, %u, %08x) "
  22.                 "returned a buffer with a null handle",
  23.                 mIdentity, index, w, h, format, usage);
  24.         err = mSharedBufferClient->getStatus();
  25.         LOGE_IF(err, "Surface (identity=%d) state = %d", mIdentity, err);
  26.         if (!err && buffer->handle != NULL) {
  27.             err = getBufferMapper().registerBuffer(buffer->handle);
  28.           /*上面获得handle 还没client端地址, 只是service 端的地址有了,
  29.    所以call registerBuffer
  30.           把他再通过gralloc_map map 到client 端,何其繁杂,都是mmu惹的祸
  31.   */
  32.             LOGW_IF(err, "registerBuffer(...) failed %d (%s)",
  33.                     err, strerror(-err));
  34.             if (err == NO_ERROR) {
  35.                 currentBuffer = buffer;
  36.                 currentBuffer->setIndex(index);
  37.             }
  38.         } else {
  39.             err = err<0 ? err : status_t(NO_MEMORY);
  40.         }
  41.     }
  42.     return err;
  43. }


  4. unlockAndPost 简单列下代码:
  status_t Surface::unlockAndPost()  (android_view_Surface.cpp)
  {
    if (mLockedBuffer == 0) {
        LOGE("Surface::unlockAndPost failed, no locked buffer");
        return INVALID_OPERATION;
    }
    status_t err = mLockedBuffer->unlock();
    LOGE_IF(err, "failed unlocking buffer (%p)", mLockedBuffer->handle);
   
    err = queueBuffer(mLockedBuffer.get());
    LOGE_IF(err, "queueBuffer (idx=%d) failed (%s)",
            getBufferIndex(mLockedBuffer), strerror(-err));
    mPostedBuffer = mLockedBuffer;
    mLockedBuffer = 0;
    return err;
}
阅读(6413) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~