Android远程代理对象BpSurface的获取过程源码分析

来源:互联网 发布:mac刷新dns 编辑:程序博客网 时间:2024/06/05 16:34

在上一篇文章Android SurfaceFlinger服务代理对象获取过程源码分析中介绍了应用程序获取SurfaceFlinger中的各种远程Binder代理对象,SurfaceFlinger为每个应用程序创建Client对象来处理应用程序的Binder请求,同时返回Client的Binder代理对象给应用程序,这样应用程序就可以通过该Binder代理对象来请求SurfaceFlinger创建Surface了,本文在前面章节的基础上 分析Surface在服务端创建对应的Layer对象过程,并将BSurface远程代理对象返回给应用程序。


SurfaceComposerClient mSession = new SurfaceComposerClient();sp<SurfaceControl> control= mSession->createSurface(0, dinfo.h, dinfo.w, PIXEL_FORMAT_RGB_565);
首先在应用程序端构造SurfaceComposerClient对象,在构造过程中,通过ComposerService类查询到SurfaceFlinger服务的远程代理对象,并通过SurfaceFlinger的远程Binder代理对象连接SurfaceFlinger,获取SurfaceFlinger为应用程序创建的Client的远程代理对象,关于应用程序查询SurfaceFlinger服务代理对象,应用程序连接SurfaceFlinger的过程请查看Android SurfaceFlinger服务代理对象获取过程源码分析。得到SurfaceComposerClient对象后,就可以调用该对象的createSurface函数来创建Surface了,同时得到一个SurfaceControl对象。

sp<SurfaceControl> SurfaceComposerClient::createSurface(        DisplayID display, //显示屏ID        uint32_t w, //图像宽度        uint32_t h, //图像高度        PixelFormat format,//图形格式        uint32_t flags)//创建的Surface类型{    String8 name;    const size_t SIZE = 128;    char buffer[SIZE];    snprintf(buffer, SIZE, "<pid_%d>", getpid());//为当前创建的Surface格式化名称:<pid_%d>    name.append(buffer);    return SurfaceComposerClient::createSurface(name, display,w, h, format, flags);}
将当前进程的ID号格式化为<pid_%d>的字符串来命名当前创建的Surface,然后调用SurfaceComposerClient的另一个重载函数createSurface来创建Surface

sp<SurfaceControl> SurfaceComposerClient::createSurface(        const String8& name,        DisplayID display,        uint32_t w,        uint32_t h,        PixelFormat format,        uint32_t flags){    sp<SurfaceControl> result;    if (mStatus == NO_ERROR) {        ISurfaceComposerClient::surface_data_t data;//mClient为服务端Client的远程代理对象BpSurfaceComposerClient,这里请求服务端Client创建Surface        sp<ISurface> surface = mClient->createSurface(&data, name,display, w, h, format, flags);        if (surface != 0) {//根据服务端返回来的ISurface,surface_data_t及当前SurfaceComposerClient对象来构造SurfaceControl对象            result = new SurfaceControl(this, surface, data);        }    }    return result;}
在Android SurfaceFlinger服务代理对象获取过程源码分析中我们知道,应用程序获得Client的远程代理对象BpSurfaceComposerClient后,保存到成员变量mClient中,这里就是通过Client的远程代理对象BpSurfaceComposerClient向服务端的Client请求创建Surface,并得到BSurface的远程Binder代理对象BpSurface,接着利用得到的BpSurface对象及SurfaceComposerClient对象为应用程序创建一个SurfaceControl对象。ISurface也是基于Binder进程通信框架设计的,其在Binder通信框架中的类关系图如下:


由于ISurfaceComposerClient也是基于Binder通信框架的,因此BpSurfaceComposerClient向服务端的Client请求创建Surface的过程分为客户端进程和服务端进程。

客户端进程:

frameworks\native\libs\gui\ISurfaceComposerClient.cpp

virtual sp<ISurface> createSurface( surface_data_t* params,const String8& name,DisplayID display,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags){Parcel data, reply;data.writeInterfaceToken(ISurfaceComposerClient::getInterfaceDescriptor());data.writeString8(name);data.writeInt32(display);data.writeInt32(w);data.writeInt32(h);data.writeInt32(format);data.writeInt32(flags);remote()->transact(CREATE_SURFACE, data, &reply);params->readFromParcel(reply);return interface_cast<ISurface>(reply.readStrongBinder());}
服务端进程:

frameworks\native\libs\gui\ISurfaceComposerClient.cpp

status_t BnSurfaceComposerClient::onTransact(    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags){     switch(code) {        case CREATE_SURFACE: {            CHECK_INTERFACE(ISurfaceComposerClient, data, reply);            surface_data_t params;            String8 name = data.readString8();            DisplayID display = data.readInt32();            uint32_t w = data.readInt32();            uint32_t h = data.readInt32();            PixelFormat format = data.readInt32();            uint32_t flags = data.readInt32();            sp<ISurface> s = createSurface(¶ms, name, display, w, h,format, flags);            params.writeToParcel(reply);            reply->writeStrongBinder(s->asBinder());            return NO_ERROR;        } break;        default:            return BBinder::onTransact(code, data, reply, flags);    }}
createSurface函数在BnSurfaceComposerClient的子类Client中实现

frameworks\native\services\surfaceflinger\SurfaceFlinger.cpp

sp<ISurface> Client::createSurface(        ISurfaceComposerClient::surface_data_t* params,        const String8& name,        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,        uint32_t flags){//构造一个MessageCreateSurface消息    sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(),params, name, this, display, w, h, format, flags);//将消息投递到SurfaceFlinger的mEventQueue队列中,并睡眠等待消息处理    mFlinger->postMessageSync(msg);//当消息得到处理后,线程唤醒,读取处理结果    return static_cast<MessageCreateSurface*>( msg.get() )->getResult();}
关于SurfaceFlinger的消息队列这里不做分析。MessageCreateSurface消息被投递到SurfaceFlinger的mEventQueue队列中后,MessageCreateSurface类的handler函数被调用,用来处理MessageCreateSurface消息。

virtual bool handler() {result = flinger->createSurface(params, name, client,display, w, h, format, flags);return true;}
这里又调用SurfaceFlinger的createSurface函数来创建Surface

sp<ISurface> SurfaceFlinger::createSurface(        ISurfaceComposerClient::surface_data_t* params,        const String8& name,        const sp<Client>& client,        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,        uint32_t flags){    sp<LayerBaseClient> layer;    sp<ISurface> surfaceHandle;//图像的宽高必须大于0    if (int32_t(w|h) < 0) {        ALOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",int(w), int(h));        return surfaceHandle;    }//根据flag来判断请求创建的Surface类型,实际创建的是LayerBaseClient对象    sp<Layer> normalLayer;    switch (flags & eFXSurfaceMask) {        case eFXSurfaceNormal:            normalLayer = createNormalSurface(client, d, w, h, flags, format);            layer = normalLayer;            break;        case eFXSurfaceBlur:            // for now we treat Blur as Dim, until we can implement it            // efficiently.        case eFXSurfaceDim:            layer = createDimSurface(client, d, w, h, flags);            break;        case eFXSurfaceScreenshot:            layer = createScreenshotSurface(client, d, w, h, flags);            break;    }    if (layer != 0) {//初始化LayerBaseClient对象        layer->initStates(w, h, flags);        layer->setName(name);        ssize_t token = addClientLayer(client, layer);//从LayerBaseClient对象中取出BSurface本地对象        surfaceHandle = layer->getSurface();        if (surfaceHandle != 0) {//初始化参数params            params->token = token;            params->identity = layer->getIdentity();            if (normalLayer != 0) {                Mutex::Autolock _l(mStateLock);                mLayerMap.add(layer->getSurfaceBinder(), normalLayer);            }        }        setTransactionFlags(eTransactionNeeded);    }    return surfaceHandle;}
该函数首先根据应用程序发送过来的参数来读取请求创建Surface的类型,目前Android系统定义了4种类型的Layer,即eFXSurfaceNormal、eFXSurfaceBlur、eFXSurfaceDim、eFXSurfaceScreenshot。构造完并初始化LayerBaseClient对象,最后从LayerBaseClient对象中取得BSurface本地对象,然后将BSurface对象的远程Binder代理对象返回给应用程序。


sp<Layer> SurfaceFlinger::createNormalSurface(        const sp<Client>& client, DisplayID display,        uint32_t w, uint32_t h, uint32_t flags,        PixelFormat& format){    // initialize the surfaces    switch (format) { // TODO: take h/w into account    case PIXEL_FORMAT_TRANSPARENT:    case PIXEL_FORMAT_TRANSLUCENT:        format = PIXEL_FORMAT_RGBA_8888;        break;    case PIXEL_FORMAT_OPAQUE:#ifdef NO_RGBX_8888        format = PIXEL_FORMAT_RGB_565;#else        format = PIXEL_FORMAT_RGBX_8888;#endif        break;    }#ifdef NO_RGBX_8888    if (format == PIXEL_FORMAT_RGBX_8888)        format = PIXEL_FORMAT_RGBA_8888;#endif//构造Layer对象    sp<Layer> layer = new Layer(this, display, client);    status_t err = layer->setBuffers(w, h, format, flags);    if (CC_LIKELY(err != NO_ERROR)) {        ALOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));        layer.clear();    }    return layer;}
该函数首先判断图像格式,然后构造一个Layer对象,接着为该Layer对象设置缓冲区buffer,上图显示了Layer类的继承关系,在构造Layer对象时,其父类的构造函数会被依次调用。
Layer::Layer(SurfaceFlinger* flinger,        DisplayID display, const sp<Client>& client)    :   LayerBaseClient(flinger, display, client),        mTextureName(-1U),        mQueuedFrames(0),        mCurrentTransform(0),        mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),        mCurrentOpacity(true),        mRefreshPending(false),        mFrameLatencyNeeded(false),        mFrameLatencyOffset(0),        mFormat(PIXEL_FORMAT_NONE),        mGLExtensions(GLExtensions::getInstance()),        mOpaqueLayer(true),        mNeedsDithering(false),        mSecure(false),        mProtectedByApp(false){    mCurrentCrop.makeInvalid();    glGenTextures(1, &mTextureName);}
Layer的父类LayerBaseClient构造过程:
LayerBaseClient::LayerBaseClient(SurfaceFlinger* flinger, DisplayID display,        const sp<Client>& client)    : LayerBase(flinger, display),      mHasSurface(false),      mClientRef(client),      mIdentity(uint32_t(android_atomic_inc(&sIdentity))){}
LayerBaseClient的父类LayerBase的构造过程:
LayerBase::LayerBase(SurfaceFlinger* flinger, DisplayID display)    : dpy(display), contentDirty(false),      sequence(uint32_t(android_atomic_inc(&sSequence))),      mFlinger(flinger), mFiltering(false),      mNeedsFiltering(false),      mOrientation(0),      mPlaneOrientation(0),      mTransactionFlags(0),      mPremultipliedAlpha(true), mName("unnamed"), mDebug(false){    const DisplayHardware& hw(flinger->graphicPlane(0).displayHardware());    mFlags = hw.getFlags();}
由于Layer继承于RefBase类,同时实现了该类的onFirstRef函数,在前面就介绍了,当第一次强引用RefBase的子类对象,并且该子类对象实现了onFirstRef函数,onFirstRef函数会被自动调用,Layer对象也不例外:
void Layer::onFirstRef(){    LayerBaseClient::onFirstRef();    // Creates a custom BufferQueue for SurfaceTexture to use    sp<BufferQueue> bq = new SurfaceTextureLayer();    mSurfaceTexture = new SurfaceTexture(mTextureName, true,GL_TEXTURE_EXTERNAL_OES, false, bq);    mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));    mSurfaceTexture->setFrameAvailableListener(new FrameQueuedListener(this));    mSurfaceTexture->setSynchronousMode(true);#ifdef TARGET_DISABLE_TRIPLE_BUFFERING#warning "disabling triple buffering"    mSurfaceTexture->setBufferCountServer(2);#else    mSurfaceTexture->setBufferCountServer(3);#endif}
SurfaceTextureLayer也是基于Binder通信框架设计的:
这里就是为当前创建的Layer构造并初始化SurfaceTexture对象,该SurfaceTexture对象用来管理BufferQueue。回到SurfaceFlinger的创建 普通Surface函数createNormalSurface,构造完Layer对象后,还需根据图像大小,格式来设置Layer对象中的buffer
status_t Layer::setBuffers( uint32_t w, uint32_t h,                            PixelFormat format, uint32_t flags){    // this surfaces pixel format    PixelFormatInfo info;    status_t err = getPixelFormatInfo(format, &info);    if (err) {        ALOGE("unsupported pixelformat %d", format);        return err;    }    // the display's pixel format    const DisplayHardware& hw(graphicPlane(0).displayHardware());    uint32_t const maxSurfaceDims = min(hw.getMaxTextureSize(), hw.getMaxViewportDims());    // never allow a surface larger than what our underlying GL implementation    // can handle.    if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {        ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));        return BAD_VALUE;    }    PixelFormatInfo displayInfo;    getPixelFormatInfo(hw.getFormat(), &displayInfo);    const uint32_t hwFlags = hw.getFlags();        mFormat = format;    mSecure = (flags & ISurfaceComposer::eSecure) ? true : false;    mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false;    mOpaqueLayer = (flags & ISurfaceComposer::eOpaque);    mCurrentOpacity = getOpacityForFormat(format);    mSurfaceTexture->setDefaultBufferSize(w, h);    mSurfaceTexture->setDefaultBufferFormat(format);    mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));    // we use the red index    int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED);    int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED);    mNeedsDithering = layerRedsize > displayRedSize;    return NO_ERROR;}
最后返回到SurfaceFlinger的createSurface函数设置Layer的当前状态及名称,同时将当前创建的Layer添加到Client的窗口列表及SurfaceFlinger维护的Z秩序列表中
layer->initStates(w, h, flags);layer->setName(name);ssize_t token = addClientLayer(client, layer);
将当前Layer添加的Client及SurfaceFlinger维护的列表中
ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,const sp<LayerBaseClient>& lbc){    // attach this layer to the client    size_t name = client->attachLayer(lbc);    Mutex::Autolock _l(mStateLock);    // add this layer to the current state list    addLayer_l(lbc);    return ssize_t(name);}
函数调用attachLayer将当前Layer添加到当前应用程序在SurfaceFlinger中的Client的mLayers列表中
DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;size_t Client::attachLayer(const sp<LayerBaseClient>& layer){    Mutex::Autolock _l(mLock);    size_t name = mNameGenerator++;    mLayers.add(name, layer);    return name;}
接着调用函数addLayer_l将当前创建的Layer添加到SurfaceFlinger中
status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer){    ssize_t i = mCurrentState.layersSortedByZ.add(layer);    return (i < 0) ? status_t(i) : status_t(NO_ERROR);}

完成Layer对象的创建及设置后,调用当前创建的Layer对象的getSurface()函数来创建一个BSurface对象,getSurface()函数实现在Layer的父类LayerBaseClient中
sp<ISurface> LayerBaseClient::getSurface(){    sp<ISurface> s;    Mutex::Autolock _l(mLock);    LOG_ALWAYS_FATAL_IF(mHasSurface,"LayerBaseClient::getSurface() has already been called");    mHasSurface = true;    s = createSurface();    mClientSurfaceBinder = s->asBinder();    return s;}
createSurface()用于创建一个BSurface对象,同时将创建的BSurface的Binder本地对象保存到LayerBaseClient的父类LayerBase的成员变量mClientSurfaceBinder中。
sp<ISurface> LayerBaseClient::createSurface(){    sp<ISurface> sur(new BSurface(mFlinger, this));    return sur;}
层层返回到SurfaceFlinger的createSurface函数,该函数最终返回一个BSurface对象,最后在BnSurfaceComposerClient的onTransact函数中通过writeStrongBinder(s->asBinder())将BSurface的Binder本地对象写入到Binder驱动中,应用程序端BpSurfaceComposerClient通过reply.readStrongBinder()从Binder驱动中读取BSurface的Binder远程代理对象,并通过interface_cast<ISurface>创建BSurface的远程代理对象BpSurface,到此Surface就创建完成了,现在来总结一下Surface的整个创建过程:
1.应用程序进程通过SurfaceComposerClient对象向SurfaceFlinger请求创建Surface;
2.SurfaceComposerClient对象借助Client的远程代理对象BpSurfaceComposerClient向Client请求创建Surface;
3.Client接收到BpSurfaceComposerClient的CREATE_SURFACE请求后,向SurfaceFlinger的事件队列发送MessageCreateSurface消息;
4.MessageCreateSurface消息处理过程中,使用SurfaceFlinger来创建Surface;
5.SurfaceFlinger根据参数创建并初始化Layer对象;
6.创建BSurface对象,并将该对象的Binder远程对象返回给应用程序进程。


原创粉丝点击